Python

「Flask笔记」 jinja2模板总结

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>

Recent Posts

2023 年 WordPress 中最棒的多语言翻译插件推荐

担心如何翻译您的网站语言以支持…

12月 ago

2023 年 WordPress 中最棒的可视化页面构建器插件推荐

在设计任何页面或网站时,对于不…

12月 ago

Ella 多用途 Shopify 主题

Shopify 主题市场上有许…

1年 ago

AI Engine Pro

喵容今天带来的 AI Engi…

1年 ago

AIKit

喵容今天为您带来 AIKit …

1年 ago

AIomatic

喵容今天为您带来AIOmati…

1年 ago