问题
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?
回答1:
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>
来源:https://stackoverflow.com/questions/31093558/get-content-from-parent-block-in-jinja2