使用 Flask 生成页面而不使用单独的模板文件
Generate pages with Flask without using separate template files
我正在努力保持最小化,所以我不想创建模板、目录结构等。我在网络上有一个简单的 CSS 文件(通过 RawGit ),我想用它来设置视图生成的页面的样式。如何在没有模板的情况下呈现页面?
from flask import Flask
application = Flask(__name__)
# <insert magic here>
# application.get_and_use_my_super_cool_CSS_file(URL)
# <insert magic here>
@application.route("/")
def hello():
return "hello world"
if __name__ == "__main__":
application.run(host = "0.0.0.0")
如果您不想将模板写成单独的文件,您可以使用render_template_string
。这通常不是一个非常有用的功能,因为很难维护编写为 Python 字符串的大型模板。 Flask 的 Jinja env 在渲染其识别的文件时也提供了一些额外的帮助,例如为 HTML 文件打开自动转义,因此直接从字符串渲染时需要更加小心。
return render_template_string('''<!doctype html>
<html>
<head>
<link rel="stylesheet" href="css url"/>
</head>
<body>
<p>Hello, World!</p>
</body>
</html>
'''
我正在努力保持最小化,所以我不想创建模板、目录结构等。我在网络上有一个简单的 CSS 文件(通过 RawGit ),我想用它来设置视图生成的页面的样式。如何在没有模板的情况下呈现页面?
from flask import Flask
application = Flask(__name__)
# <insert magic here>
# application.get_and_use_my_super_cool_CSS_file(URL)
# <insert magic here>
@application.route("/")
def hello():
return "hello world"
if __name__ == "__main__":
application.run(host = "0.0.0.0")
如果您不想将模板写成单独的文件,您可以使用render_template_string
。这通常不是一个非常有用的功能,因为很难维护编写为 Python 字符串的大型模板。 Flask 的 Jinja env 在渲染其识别的文件时也提供了一些额外的帮助,例如为 HTML 文件打开自动转义,因此直接从字符串渲染时需要更加小心。
return render_template_string('''<!doctype html>
<html>
<head>
<link rel="stylesheet" href="css url"/>
</head>
<body>
<p>Hello, World!</p>
</body>
</html>
'''