here’s my generalized question:
base.html :
<html>
<head>
{% if title %}
<title>{{title}}</title>
{% else %}
<title>test</title>
{% endif %}
</head>
<body>
{% block content %} {% endblock %}
</body>
</html>
How can I write a function that can directly create a block? maybe something like:
@app.route("/foo")
def foo():
content = "<h1>this is foo page</h1>"
return render_html("base.html", content = content)
You are trying to render HTML in your Jinja2 template without HTML escaping. By default, Jinja2 is configured to do automatic escaping of all variables you interpolate.
This means that
is actually rendered as
so you don’t accidentally use HTML in your pages where you didn’t mean to. This is very important to protect against Cross Site Scripting (XSS) attacks.
If you are going to bypass this automatic escaping, and deliberately insert HTML into your templates, you must make sure you know what you are doing – never allow unescaped user input to get into these variables.
With the background lesson and security warnings out of the way, if you do know what you are doing, you can explicitly mark values as “safe” in your template, so they will not be escaped. Just use Jinja2’s builtin filter, safe, like so:
In your case, I think you also wanted to have a block, so you can override with template inheritance. For an example of that, play with this complete example app
test.py:
templates/base.html:
templates/child.html: