include 和 set 语句

Flask 学习笔记

一、include 语句


        include 语句可以把一个模板引入到另外一个模板中,类似于把一个 html 的代码 copy 到另外一个 html 的指定位置使用。

  1. 创建 header.html 文件
	<body>
	    <h1>这是头部</h1>
	    <hr>
	    <br>
	</body>
  1. 创建 footer.html 文件
	<body>
	    <br>
	    <hr>
	    <h1>这是尾部</h1>
	</body>
  1. 在 detail.html 引入使用
	<body>
	    {% include "commit/header.html" %}
	
	    {% include "commit/footer.html" %}
	</body>



二、赋值(set)语句


2.1、全局赋值

        有时候我们想在在模板中添加变量,这时候赋值语句(set)就派上用场了。全局赋值,直接使用即可。

	{% set commit='全局设值' %}
    <p>{{commit}}</p>

2.2、局部赋值

        如果不想让一个变量污染全局环境,可以使用 with 语句来创建一个内部的作用域,将 set 语句放在其中,这样创建的变量只在 with 代码块中才有效。

	<body>
	    {% include "commit/header.html" %}
	
	    {% set commit='全局设值' %}
	    <p>{{commit}}</p>
	
	    {% with %}
	        <li>{{commit}}</li>
	        {% set foo=42 %}
	        <li>{{foo}}</li>
	    {% endwith %}
	
	    <p>这里访问不到 foo:{{foo}}</p>
	    
	    {% include "commit/footer.html" %}
	</body>

也可以在with的后面直接添加变量,比如以上的写法可以修改成这样:

    {% with foo2="可用在这直接设值" %}
        <li>{{foo2}}</li>
    {% endwith %}

赋值可以为 字典、列表、元组 等:

    {% with nav=('Python', 'Java', 'PHP') %}
        <li>{{nav}}</li>
    {% endwith %}

    {% with dic={'Python': 46, 'Java': 37, 'PHP': 33} %}
        {% for k,v in dic.items() %}
            <ul><li>{{k}} -> {{v}}</li></ul>
        {% endfor %}
    {% endwith %}

    {% with lis=['Python', 'Java', 'PHP'] %}
        <li>{{lis}}</li>
    {% endwith %}
发布了145 篇原创文章 · 获赞 1 · 访问量 5851

猜你喜欢

转载自blog.csdn.net/qq_43621629/article/details/105570413