0

这是我的笼统问题:

base.html:

<html>
  <head>
    {% if title %}
    <title>{{title}}</title>
    {% else %}
    <title>test</title>
    {% endif %}
  </head>
  <body>
    {% block content %} {% endblock %}
  </body>
</html>

如何编写可以直接创建块的函数?也许是这样的:

@app.route("/foo")
def foo():
    content = "<h1>this is foo page</h1>"
    return render_html("base.html", content = content)
4

2 回答 2

2

您正试图在您的Jinja2模板中呈现 HTML而不进行 HTML 转义。默认情况下,Jinja2 配置为自动转义您插入的所有变量。

这意味着

<h1>this is foo page</h1>

实际上呈现为

&lt;h1&gt;this is foo page&lt;/h1&gt;

这样您就不会在您无意的页面中意外使用 HTML。这对于防止跨站点脚本 (XSS)攻击非常重要。

如果您打算绕过这种自动转义,并故意将 HTML 插入到您的模板中,您必须确保您知道自己在做什么——永远不要让未转义的用户输入进入这些变量。

有了背景课程和安全警告,如果您确实知道自己在做什么,您可以在模板中明确地将值标记为“安全”,这样它们就不会被转义。只需使用 Jinja2 的内置过滤器safe,如下所示:

  <body>
    {{ content | safe }}
  </body>

在你的情况下,我认为你也想要一个块,所以你可以用模板继承覆盖。例如,使用这个完整的示例应用程序

测试.py:

import flask

app = flask.Flask(__name__)

@app.route("/foo")
def foo():
    content = "<h1>this is foo content</h1>"
    return flask.render_template("base.html", content=content)

@app.route("/bar")
def bar():
    content = "<h1>this is bar content</h1>"
    return flask.render_template("child.html", content=content)

if __name__ == "__main__":
    app.run(debug=True)

模板/base.html:

<html>
  <head>
    {% if title %}
    <title>{{title}}</title>
    {% else %}
    <title>test</title>
    {% endif %}
  </head>
  <body>
    {% block content %}{{ content | safe }}{% endblock %}
  </body>
</html>

模板/child.html:

{% extends "base.html" %}
{% block content %}
  {{ super() }}
  <h2>And this bit comes from the child template</h2>
{% endblock %}
于 2013-01-29T18:52:51.603 回答
0

看法 :

@app.route("/foo")
def foo():
content = "<h1>this is foo page</h1>"
return render_template("base.html", content = content)

base.html:

<html>
<head>
{% if title %}
<title>{{title}}</title>
{% else %}
<title>test</title>
{% endif %}
</head>
<body>
{% block content %} 
{% if content %}
{{ content | safe }}
{% else %}
No content provided
{% endif %}
{% endblock %}
</body>
</html>
于 2013-01-29T15:48:22.033 回答