get content from parent block in jinja2

好久不见. 提交于 2020-06-25 21:15:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!