【问题标题】:Incorporating Python inside a Flask HTML page在 Flask HTML 页面中加入 Python
【发布时间】:2017-08-15 16:24:38
【问题描述】:

假设我有一个包含一些 HTML 代码的 flask_app.py 应用程序,我想打印一个 python 变量:

from flask import Flask
app = Flask(__name__)

myString = foo

@app.route("/")
def hello():
  return """<!DOCTYPE html>
        <html>
            <body>
                <p>""" + myString + """
            </body>
        </html>"""

现在这工作正常,但不是真正可扩展的。我在 index.html 文件中有基本的 HTML sn-p,我怎样才能使用它产生相同的结果(并打印 myString )?

【问题讨论】:

  • IIUC 你想要类似于带有 RoR 的 erb 文件,对吧?你看过 jinja2 吗?
  • 您的问题的答案在烧瓶文档中。具体在the section that introduces templates
  • @SrinivasSuresh 是的,类似的东西。如果它允许在 html 中传递 python 变量,我将看看 jinja2。
  • @stamaimer 和 Rob 是正确的。烧瓶文档专门讨论了此类内容,甚至他们将您指向 jinja2 文档,因此请阅读它们
  • @Robᵩ 是的,完美!今天刚开始使用 Flask,我应该先阅读。

标签: python html python-2.7 flask


【解决方案1】:

把这个文件放在/tmp/x.py:

from flask import Flask, render_template
app = Flask(__name__)

myString = 'foo'

@app.route("/")
def hello():
  return render_template('index.html', myString=myString)

app.run(debug=True)

这个文件在/tmp/templates/index.html:

<!DOCTYPE html>
<html>
    <body>
        <p>{{ myString }}
    </body>
</html>

然后运行这个命令:

python /tmp/x.py

参考:

http://flask.pocoo.org/docs/0.12/quickstart/#rendering-templates

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-09
    • 1970-01-01
    • 1970-01-01
    • 2018-03-28
    • 1970-01-01
    • 2020-09-17
    • 1970-01-01
    相关资源
    最近更新 更多