「Flask笔记」 jinja2模板总结

「Flask笔记」 jinja2模板总结

资源介绍参数
资源类别: Python
如遇问题: 联系客服/留言反馈
释放双眼,带上耳机,听听看~!
flask – jinja2模板模板导入在项目根目录下创建一个templates目录,flask会自动在这里寻找模板如果不想把模板放在这个目录下的话,那么可以在初始化flask的时候指定template_folder来指定模板的路径模板传递参数使用render_template渲染模板的时候可以传递关键字

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>
声明:本文为原创作品,版权归作者所有。未经许可,不得转载或用于任何商业用途。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

给TA打赏
共{{data.count}}人
人已打赏
0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索