I need to get content from particular block in Jinja2 by console script. For example
//global template
{% block target %}
<some_content_from_top>
{% endblock %}
//parent template
{% extends 'top.html' %}
{% block target %}
<some_content_from_parent>
{% endblock %}
//child template
{% extends 'parent.html' %}
{% block target %}
<some_content>
{% endblock %}
I can use something like that to get content from this block in particular template without inheritanse
template_source = self.env.loader.get_source(self.env, template_path)[0]
parsed_content = self.env.parse(template_source).body
# do something with blck content
But how I can get content from all parent templates.Of course I can get parent template name from Extends block and do the same manipulations over and over again tiil I get top-level template without Extends block. But maybe there are more efficient way?
The Jinja documentation about templates is pretty clear about what a block does: All the block tag does is tell the template engine that a child template may override those placeholders in the template.
from_string . Jinja 2 provides a Template class that can be used to do the same, but with optional additional configuration. Jinja 1 performed automatic conversion of bytes in a given encoding into unicode objects.
When autoescaping is enabled, Jinja2 will filter input strings to escape any HTML content submitted via template variables. Without escaping HTML input the application becomes vulnerable to Cross Site Scripting (XSS) attacks. Unfortunately, autoescaping is False by default.
You can use Jinja2's super
function to include content from a block in a parent template.
top.html
{% block target %}
<some_content_from_top>
{% endblock %}
parent.html
{% extends 'top.html' %}
{% block target %}
<some_content_from_parent>
{{ super() }}
{% endblock %}
child.html
{% extends 'parent.html' %}
{% block target %}
{{ super() }}
<some_content>
{% endblock %}
This will result in:
<some_content_from_parent>
<some_content_from_top>
<some_content>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With