「Flask笔记」 jinja2模板总结

栏目: Python · 发布时间: 5年前

内容简介:在项目根目录下创建一个如果不想把模板放在这个目录下的话,那么可以在初始化上面这种写法不够优雅,还可以修改成使用关键字参数

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>
  1. 使用字典(关键字参数比较多的时候)
# 省略初始化
@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>

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Little Prover

The Little Prover

Daniel P. Friedman、Carl Eastlund / The MIT Press / 2015-7-10 / USD 38.00

[FROM www.amazon.com]: The Little Prover introduces inductive proofs as a way to determine facts about computer programs. It is written in an approachable, engaging style of question-and-answer, wi......一起来看看 《The Little Prover》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

URL 编码/解码
URL 编码/解码

URL 编码/解码

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具