内容简介:在项目根目录下创建一个如果不想把模板放在这个目录下的话,那么可以在初始化上面这种写法不够优雅,还可以修改成使用关键字参数
flask -- jinja2模板
模板导入
在项目根目录下创建一个 templates
目录,flask会自动在这里寻找模板
如果不想把模板放在这个目录下的话,那么可以在初始化 flask
的时候指定 template_folder
来指定模板的路径
模板传递参数
使用 render_template
渲染模板的时候可以传递 关键字参数
到模板文件中
关键字参数的方法
1. 直接添加到视图函数中
# 省略初始化
@app.route('/template')
def template():
return render_template('index.html',foo='hello, world!')
<!-- 省略其他标签 -->
<p>{{ foo }}</p>
- 使用字典(关键字参数比较多的时候)
# 省略初始化
@app.route('/template')
def template():
context={
'author':'ding',
'age':18,
'say':'hello, world!'
}
return render_template('index.html',context=context)
<!-- 省略其他标签 -->
<p>{{context.author}}</p>
<p>{{context.age}}</p>
<p>{{context.say}}</p>
上面这种写法不够优雅,还可以修改成使用关键字参数
# 省略初始化
@app.route('/template')
def template():
context={
'author':'ding',
'age':18,
'say':'hello, world!'
}
return render_template('index.html',**context)
<!-- 省略其他标签 -->
<p>{{author}}</p>
<p>{{age}}</p>
<p>{{say}}</p>
模板中使用url_for
在jinja2模板中使用 url_for
和在视图函数中使用是基本相同的
语法: {{url_for('视图函数名称',[其他参数])}}
# 省略初始化
@app.route('/')
def hello_world():
return render_template('index.html')
@app.route('/login/')
def login():
return render_template('login.html')
<!-- 省略其他标签 -->
<!-- index.html -->
<a href="{{ url_for('login') }}">click me</a>
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Distributed Algorithms
Nancy A. Lynch / Morgan Kaufmann / 1996-3-15 / USD 155.00
In "Distributed Algorithms", Nancy Lynch provides a blueprint for designing, implementing, and analyzing distributed algorithms. She directs her book at a wide audience, including students, programmer......一起来看看 《Distributed Algorithms》 这本书的介绍吧!