1、flask的默认模板是jinja ,模板默认目录是你开发的应用目录下的templates ,例:app/templates
2、导入模板传递函数包 :from flask import render_template
render——template(arguments)主要参数:第一个参数是模板名,之后的参数是模板中需要填充的动态变量参数。
例:
render_template("home.html",
title=first_article.get("title"),
published=first_article.get("published"),
summary=first_article.get("summary"))
在模板中用双大括号表示变量的内容:
例:
<html>
<head>
<title>Headlines</title>
</head>
<body>
<h1>Headlines</h1>
<b>{{title}}</b><br />
<i>{{published}}</i><br />
<p>{{summary}}</p>
</body>
</html>
3、模板高级用法:
- 使用模板对象: Python内置的数据结构和对象(包括变量、对象、列表、字典等等)都能被jinja识别和处理 ,处理方式和在Python中一致。如上面的例子可以简化为:
render_template("home.html", article=first_article)
<b>{{article.title}}</b><br /> <i>{{article.published</i><br /> <p>{{article.summary}}</p>
- 使用逻辑判断:模板中可以使用for循环、if...else...等逻辑判断功能,用{% %}来表示逻辑控制功能如:
<body> <h1>Headlines</h1> {% for article in articles %} <b>{{article.title}}</b><br /> <i>{{article.published}}</i><br /> <p>{{article.summary}}</p> <hr /> {% endfor %} </body
- 添加超链接:
<b><a href="{{article.link}}">{{article.title}}</a></b><br />