标签:存储 基础 temp out Python一 ret 存在 image htm
根目录下的基础代码 flaskStudy.py
from flask import Flask, render_template
app = Flask(__name__)
args = {
"sex": "male",
"addr": "beijing",
"like": "tea",
"age": 65
}
@app.route("/fromuser/<name>")
def user(name):
return render_template("user.html", user=name,args=args)
if __name__ == ‘__main__‘:
app.run()
条件控制
在根目录下的templates目录下创建user.html, 内容如下。
{% if user %}
hello, {{ user }} !
{% else %}
hello, Strange !
{% endif %}
功能为: 判断user是否存在。
运行结果

循环控制
在user.html中增加如下代码
<ul>
{% for arg in args %}
<li>{{ arg }}</li>
{% endfor %}
</ul>
功能: 通过for循环打印user的所有属性。
运行结果:

宏
类似python代码中的函数
1、 在代码中直接编写引用。
{% if user %}
hello, {{ user }} !
{% else %}
hello, Strange !
{% endif %}
{% macro render_arg(arg) %}
<li>{{ arg }}</li>
{% endmacro %}
{% for arg in args %}
{{ render_arg(arg) }}
{% endfor %}
功能: 创建一个宏 render_arg, 在for循环中调用宏。
运行结果:

2、像python一样, 把宏(函数)保存在单独的文件中, 然后在需要的模块中导入。
macros.html
{% macro render_arg(arg) %}
<li>{{ arg }}</li>
{% endmacro %}
user.html
{% if user %}
hello, {{ user }} !
{% else %}
hello, Strange !
{% endif %}
{% import ‘macros.html‘ as macros %}
{% for arg in args %}
{{ macros.render_arg(arg) }}
{% endfor %}
包含
应用场景: 有一段代码, 在多处被频繁引用,为了避免多次编辑,可将这段代码存储于一个单独的文件中, 在需要的模块中引用。
common.html : 存储利用频繁的代码片段
{% include ‘common.html‘ %} : 在需要的模块中引用common.html中的代码
示例:
common.html
{% if user %}
hello, {{ user }} !
{% else %}
hello, Strange !
{% endif %}
user.html
{% include"common.html" %}
{% import ‘macros.html‘ as macros %}
{% for arg in args %}
{{ macros.render_arg(arg) }}
{% endfor %}
标签:存储 基础 temp out Python一 ret 存在 image htm
原文地址:https://www.cnblogs.com/kongzhagen/p/12986579.html