模版

来源:互联网 发布:自动打印软件 编辑:程序博客网 时间:2024/04/27 01:26

Jinja2模版引擎

# templates/index.html<h1>Hello World!</h1># templates/user.html<h1>Hello, {{name}}</h1>

渲染模版

from flask import Flask, render_templates@app.route('/')def index():    return render_template('index.html')@app.route('/user/<name>')def user(name):    return render_template('user.html', name=name)

render_template 函数把Jinja2模版引擎集成到了程序中。render_template函数的第一个参数是模版的文件名。随后的参数都是键值对,表示模版中变量对应的真实值。

变量

可以使用过滤器修改变量,过滤器名添加在变量名之后,中间使用竖线分割

Hello, {{name|capitalize}}
过滤器名 说明 safe 渲染值时不转义 capitalize 把值的首字母转换成大写,其他字母转换成小写 lower 把值转换成小写 upper 把值转换成大写 title 把值中的每个单词的首字母都转换成大写 trim 把值的首尾空格去掉 striptags 渲染之前把值中的所有的HTML标签都删掉

默认情况下,处于安全考虑,Jinja会转义所有变量。例如,如果一个变量的值为’

hello

‘,Jinja2 会将其渲染成’<h1>Hello</h1&gt’,浏览器能显示这个h1元素,但不会进行解释。很多情况下需要显示变量中存储的html代码,这时就可以使用safe过滤器。

控制结构

{%if user%}    Hello, {{user}}!{% else %}    Hello,Stranger{% endif %}
<ul> {% for comment in comments %}     <li>{{comment}}</li> {% endfor %}</ur>

Jinja2还支持宏,类似python代码中的函数

{% macro render_comment(comment) %}    <li>{{comment}}</li>{% endmacro %}<url>    {% for comment in comments %}        {{render_comment(comment)}}    {% endfor %}</ur>

为了重复使用宏,我们可以将其保存在单独的文件中,然后在需要使用的模版中导入:

{% import 'macros.html' as macros %}<ul>    {% for comment in comments %}        {{macros.render_comment(comment)}}    {% endfor %}</ul>

模版继承

# base.html<html>    <head>        {% block head %}        <title> {% block title %}{% endblock %} - My Application</title>        {% endblock %}    </head>    <body>    </body></html>

block 标签定义的元素可以在衍生模版中修改。

{% extends "base.html" %}{% block title %} Index {% endblock %}{% block head %}    {{super()}}    <style>    </style>{% endblock %}{% block body %}<h1> Hello,world<h1/>{% endblock %}

extends 指令声明这个模版衍生自base.html。在extends指令之后,基模版中的3个块呗重新定义,模版引擎会将其插入适当的位置。

0 0
原创粉丝点击