【发布时间】:2025-12-24 10:30:12
【问题描述】:
在完成我的 node.js 和 express 后,我目前正在学习烧瓶框架。我只是想知道我们能否像在节点 js 中那样在烧瓶中渲染 .ejs 文件。
【问题讨论】:
在完成我的 node.js 和 express 后,我目前正在学习烧瓶框架。我只是想知道我们能否像在节点 js 中那样在烧瓶中渲染 .ejs 文件。
【问题讨论】:
据我所知,没有能够呈现 .ejs(可嵌入 JavaScript 模板)文件的 Python 库。这很可能是因为 ejs 文件允许大量 JavaScript 语法(如果不是任意 JavaScript)。所以在 Python 中实现它会很痛苦。然而,有大量的模板语言支持 Python(请参阅this page on the Python wiki 以获取列表)。也就是说,理论上您可以将ejs 作为一个单独的进程执行:
import json
import subprocess
from flask import Flask
app = Flask("app")
data = {
"title": "Example",
"user": { "firstName": "World" },
"messages": [ "foo", "bar", "baz" ]
}
@app.route("/")
def hello_world():
# Note: this assumes you have globally installed ejs with: npm install -g ejs
ejsRenderer = subprocess.Popen(
["ejs", "example.ejs"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
rendered = ejsRenderer.communicate(bytes(json.dumps(data), "utf8"))[0]
ejsRenderer.stdin.close()
ejsRenderer.wait()
return rendered
app.run(host="0.0.0.0", port=8080)
【讨论】: