Flask - jinjia2模板

一、前言

参考https://www.cnblogs.com/poloyy/p/14999797.html

没有前端基础,看的有些些复杂,只了解简单用法就行,后面做网站如果是用到这模板的话再深入学习吧。

二、目录结构

一般来说 templates 就是存放模板的目录,如果遇到下面的报错,要注意下目录结构:

jinja2.exceptions.TemplateNotFound: index.html

三、实战示例一

1、jinja2 模板代码

<!DOCTYPE html>
<html>
<body>
  <h2>My name is {{ name }}, I am {{ age }} years old</h2>
</body>
</html>

2、flask 代码

  • 首先,需要 import render_template
  • 然后,视图函数调用 render_template,对模板 templates/index.html 进行渲染
  • render_template 包含有 2 个命名参数:name 和 age,模板引擎将模板 templates/index.html 中的变量进行替换
from flask import Flask, render_template

app = Flask(__name__)


@app.route('/')
def index():
    return render_template('index.html', name='tom', age=10)


app.run(debug=True)

浏览器运行效果:

 四、实战示例二

1、分界符

jinja2 模板文件混合 html 语法与 jinja2 语法,使用分界符区分 html 语法与 jinja2 语法。有 5 种常见的分界符:

  • {{ 变量 }},将变量放置在 {{ 和 }} 之间;
  • {% 语句 %},将语句放置在 {% 和 %} 之间;
  • {# 注释 #},将注释放置在 {# 和 #} 之间;
  • ## 注释,将注释放置在 # 之后

2、变量 语法

jinjia2模板中,使用{{var}}包围的标识符称为变量,模板渲染会将其替换为python中的变量,语法如下:{{ 变量 }}

3、jinjia2模板

包含有 3 种类型的变量:字符串、列表、字典,它们会被替换为同名的 Python 变量

<html>
{{ string }}

<ul>
    <li> {{ list[0] }}
    <li> {{ list[1] }}
    <li> {{ list[2] }}
    <li> {{ list[3] }}
</ul>

<ul>
    <li> {{ dict['name'] }}
    <li> {{ dict['age'] }}
</ul>
</html>

4、flask代码

from flask import Flask, render_template

app = Flask(__name__)


string = 'www.imooc.com'
list = ['www', 123, (1, 2, 3), {"name": "zhangsan"}]
dict = {'name': 'zhangsan', 'age': True}


@app.route('/2')
def index2():
    return render_template('index2.html', string=string, list=list, dict=dict)


app.run(debug=True)

列表的值包含字符串、数字、元组、字典,字典的值包含字符串、布尔值。

浏览器运行的效果:

 

 

posted @ 2022-12-23 21:52  一加一  阅读(124)  评论(0编辑  收藏  举报