2-1-flask框架-扩展-模板语言-Jinja

1、模板的使用

Flask使用的是Jinja2模板,所以其语法和Django无差别

Flask 和 Django 附带了强大的 Jinja 模板语言。
对于之前没有接触过模板语言的人来说,这类语言基本上就是包含一些变量,当准备渲染呈现 HTML 时,它们会被实际的值替换。
这些变量放在标记或分隔符之前。例如:Jinja 模板使用 {% ... %} 表示循环,{{ ... }} 表示一个表达式运算结果返回。
Jinja 模板其实是 html 文件。一般情况下放在 Flask 工程的 /templates 目录下

二,示例

新建html文件

<!DOCTYPE html>
<html>
  <head>
    <title>Flask Template Example</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" media="screen">
    <style type="text/css">
      .container {
        max-width: 500px;
        padding-top: 100px;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <p>My string: {{my_string}}</p>
      <p>Value from the list: {{my_list[3]}}</p>
      <p>Loop through the list:</p>
      <ul>
        {% for n in my_list %}
        <li>{{n}}</li>
        {% endfor %}
      </ul>
    </div>
    <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
    <script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
  </body>
</html>

后端:

from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def template_test():
    return render_template('template.html', my_string="Wheeeee!", my_list=[0,1,2,3,4,5])
if __name__ == '__main__':
    app.run(debug=True)

报错:

jinja2.exceptions.TemplateNotFound: test.html

分析:
打开Flask源文件,发现template_folder=“templates”,这是是指html文件都是从当前路径下的templates中调用的.
解决方法:
方法一.在该py文件的同级目录下,建立templates文件夹,将test.html文件放入其中.

  • ps:实际是app = Flask(name)这个启动文件的同级下面,

方法二: 自定义templates路径
在创建app对象的时,增加参数template_folder=test.html所在文件路径,
例如,app = Flask(name,template_folder=r’d:\test\html_file’),这里我的test.html文件放在d:\test\html_file目录下面.

若使用方法二,则需要重新指定static文件所在的路径以及url路径
同样也在创建app对象时,增加参数static_folder和参数static_url_path,static_folder参数为js、css等前端文件,static_url_path则是路由路径.

app = Flask(__name__,template_folder=r'd:\test\html_file',
static_folder=r'd:\test\html_file',
static_url_path='/')

for循环

for循环语句笔记:
在jinja2中的for循环,跟python中的for循环基本上是一模一样的。也是for...in...的形式。并且也可以遍历所有的序列以及迭代器。但是唯一不同的是,jinja2中的for循环没有break和continue语句。

并且jinja2中的for循环还包含以下变量,可以用来获取当前的遍历状态
变量|描述
loop.index 当前迭代的索引(从1开始)
loop.index0 当前迭代的索引(从e开始)
1oop.first 是否是第一次迭代,返回True或 False
loop.last 是否是最后一次选代,返回True或 False
11op.length 序列的长度

from flask import Flask,render_template

app = Flask(__name__)
app.config['TEMPLATES_AUTO_RELOAD'] = True

@app.route('/')
def index():
    context = {
        'users':['捡猫1','捡猫2','捡猫3'],
        'person': {
            'username': '捡猫',
            'age': 18,
            'country': 'china'
        },
        'books':[
            {
                'name': '三国演义',
                'author':'罗贯中',
                'price': 110
            },{
                'name': '西游记',
                'author':'吴承恩',
                'price': 109
            },{
                'name': '红楼梦',
                'author':'曹雪芹',
                'price': 120
            },{
                'name': '水浒传',
                'author':'施耐庵',
                'price': 119
            }
        ]
    }
    return render_template('index.html',**context)


if __name__ == '__main__':
    app.run(debug=True)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>捡猫for循环</title>
</head>
<body>
    <ul>
        {% for user in users|reverse %}
            <li>{{ user }}</li>
        {% else %}
            <li>沒有任何值</li>
        {% endfor %}
    </ul>

    <table>
        <thead>
            <tr>
                <th>用户名</th>
                <th>年龄</th>
                <th>国家</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                {% for key in person.keys() %}
                    <td>{{ key }}</td>
                {% endfor %}
            </tr>
        </tbody>
    </table>

    <table>
        <thead>
            <tr>
                <th>序号</th>
                <th>书名</th>
                <th>作者</th>
                <th>价格</th>
                <th>总数</th>
            </tr>
        </thead>
        <tbody>
            {% for book in books %}
                {% if loop.first %}
                    <tr style="background: red;">
                {% elif loop.last %}
                    <tr style="background: pink;">
                {% else %}
                    <tr>
                {% endif %}
                    <td>{{ loop.index0 }}</td>
                    <td>{{ book.name }}</td>
                    <td>{{ book.author }}</td>
                    <td>{{ book.price }}</td>
                    <td>{{ loop.length }}</td>
                </tr>
            {% endfor %}
        </tbody>
    </table>

    <table border="1">
        <tbody>
            {% for x in range(1,10) %}
                <tr>
                    {% for y in range(1,10) if y <= x %}
                        <td>{{ y }}*{{ x }}={{ x*y }}</td>
                    {% endfor %}
                </tr>
            {% endfor %}
        </tbody>
    </table>
</body>
</html>

总结:

关于模板语言

第一点:可以在视图返回一个函数,

第二点,前端可以使用 管道符,safe的方式把html,变成一个正常的,

第三点,后端可以使用markup,把html,变成一个正常的,

posted @ 2021-07-28 18:09  技术改变命运Andy  阅读(88)  评论(0编辑  收藏  举报