标签:
Flask教程(二)、templates模版速速入门 flaskstudy\
app static templates __init__.py
views.py
tmp run.py
上节咱也测试过了,都是work的。from app import app
@app.route(‘/‘)
@app.route(‘/index‘)
def index():
user = {‘nickname‘: ‘马晕‘} # fake user
return ‘‘‘
<html>
<head>
<title>Home Page</title>
</head>
<body>
<h1>Hello, ‘‘‘ + user[‘nickname‘] + ‘‘‘</h1>
</body>
</html>
‘‘‘
啷哩个浪,一大堆,这个还算是少的了,要是几千行的UI规模,程序员估计要直接喷血。没有模版是不可想象的,估计也没啥人用python开发网站了。<html>
<head>
<title>{{ title }} - wetucao</title>
</head>
<body>
<h1>Hello, {{ user.nickname }}!</h1>
</body>
</html>
和上面有些区别的是,用了两对括号{{}}来存放数据内容,本质应该是一种替换。from flask import render_template
from app import app
@app.route(‘/‘)
@app.route(‘/index‘)
def index():
user = {‘nickname‘: ‘大爷‘} # fake user
return render_template(‘index.html‘,
title=‘Home‘,
user=user)
同时为了渲染模版,咱们也得引入一个Flask的新模块,render_template.用来替换参数。<html>
<head>
<title>{{ title }} - wetucao</title>
{% else %}
<title>Welcome to wetucao</title>
{% endif %}
</head>
<body>
<h1>Hello, {{ user.nickname }}!</h1>
</body>
</html>
现在楼上的小伙子,变得有点聪明了,能够判断不同情况进行显示了。但是多人情况呢?def index():
user = {‘nickname‘: ‘大表哥‘} # fake user
posts = [ # fake array of posts
{
‘author‘: {‘nickname‘: ‘大姨夫‘},
‘body‘: ‘Beautiful day in Portland!‘
},
{
‘author‘: {‘nickname‘: ‘大保健‘},
‘body‘: ‘The Avengers movie was so cool!‘
}
]
return render_template("index.html",
title=‘Home‘,
user=user,
posts=posts)
当然, 模版文件也要有相应的修改,主要是添加了 for post in posts:<html>
<head>
{% if title %}
<title>{{ title }} - microblog</title>
{% else %}
<title>Welcome to microblog</title>
{% endif %}
</head>
<body>
<h1>Hi, {{ user.nickname }}!</h1>
{% for post in posts %}
<div><p>{{ post.author.nickname }} says: <b>{{ post.body }}</b></p></div>
{% endfor %}
</body>
</html>
简单吧?so easy!妈妈再也不用担心你不吃药<html>
<head>
{% if title %}
<title>{{ title }} - wetucao</title>
{% else %}
<title>Welcome to mwetucao/title>
{% endif %}
</head>
<body>
<div>我们吐槽: <a href="/index">主页</a></div>
<hr>
{% block content %}{% endblock %}
</body>
</html>
这个和之前有什么区别呢?{% extends "base.html" %}
{% block content %}
<h1>Hi, {{ user.nickname }}!</h1>
{% for post in posts %}
<div><p>{{ post.author.nickname }} says: <b>{{ post.body }}</b></p></div>
{% endfor %}
{% endblock %}
那是相当相当的方便啊!大表哥,亲测如下:
标签:
原文地址:http://blog.csdn.net/alvine008/article/details/42454319