像是React这个框架能够使用Hooks来写出一些function component,可以让前端不用写出一些重複冗杂的程式,
也可以让自己的程式更简洁易懂、更容易交接、更知道自己在写什么(相比于React Class的写法)。
我觉得Jinja 有着类似Hooks的效果,至少存在的用意是如此,你也可以将一些元件写成 Macros ,未来进行引用,
也可以将一些页面继承base.html,来使用共有的navbar或是footer。
https://github.com/wilsonsujames/flask_structure.git
在web内的server.py进行执行。
@app.route('/',methods=[ "GET",'POST'])def index(): a={"name":"bob","date":"12月5日","time":"23:30","peopleCount":"10位","phone":"0123456789"} Webray_in_flask=[] Webray_in_flask.append(a) hello_word_in_flask='hello hello hello' return render_template('index.html',Webray=Webray_in_flask,hello=hello_word_in_flask)
可以发现在根路由我们回传了一个string类别的hello,而在画面上我们在testbutton的旁边能看到hello的文字。
在index.html内:
{{hello}}
而在网页清单订餐资讯的表格最后一行,我们也能看到flask中回传的Webray这个list的资讯。
在index.html内:
{% for item in Webray %} <tr> <th scope="row">3</th> <td>{{item.name}}</td> <td>{{item.date}}</td> <td> {{item.time}}</td> <td> {{item.peopleCount}} </td> <td> {{item.phone}} </td> </tr> {% endfor %}
你的jinja也可以带有条件判断:
{% if name =='wilson' %} <div>blah blah blah blah</div>{% elif name == 'bob' %} <div>bob bob bob</div>{% else %} <div>la lah lah lah</div>{% endif %}
接着是Jinja的继承,藉由官网的範例base.html,在http://127.0.0.1:5566/base
可以看到:
<!DOCTYPE html><html lang="en"><head> {% block head %} <link rel="stylesheet" href="style.css" /> <title>{% block title %}{% endblock %} - My Webpage</title> {% endblock %}</head><body> <div id="content">{% block content %}{% endblock %}</div> <div id="footer"> {% block footer %} © Copyright 2008 by <a href="http://domain.invalid/">you</a>. {% endblock %} </div></body></html>
这个页面只有footer这个区块,接着大家可以到http://127.0.0.1:5566/testsuper
:
看看有神么变化,以及拔掉super()之后会发生什么事。
在macro的部分:
compoent.html
{% macro input(name, value='', type='text', size=20) -%} <input type="{{ type }}" name="{{ name }}" value="{{ value|e }}" size="{{ size }}">{%- endmacro %}
未来引用在HTML:
{% from "compoent.html" import input with context %}<p>{{ input('password', type='password') }}</p>
[day 1] 开场白[day 2] blue_print[day 3] Factory mode[day 4] JWT token[day 5] session[day 6] Jinja[day 7] Post data with Form tag[day 8] ajax with jquery[day 9] request[day 10] 将资料写进DB(pymongo)[day 11] log with mongoDB[day 12] Sql Database[day 13] 档案上传[day 14] 档案下载 及 其他传值方法[day 15] boostrap 4.6[day 16] API[day 17] Docker image化--安装篇[day 18] Docker image化--运行篇[day 19] Nginx[day 20] Docker compose[day 21] Nginx with https[day 22] pythonanywhere 部署[day 23] GCP app engine (介绍)[day 24] GCP app engine (deploy)[day 25] Flask with web cam[day 26] Flask with ML[day 27] Supervisor[day 28] Flask-Mail[day 29] Line Messaging API[day 30] 结语