从jinja2的父块获取内容 [英] get content from parent block in jinja2

查看:64
本文介绍了从jinja2的父块获取内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要通过控制台脚本从Jinja2中的特定块获取内容.例如

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

但是我如何从所有父模板中获取内容.当然,我可以从Extends块中获取父模板的名称,并一遍又一遍地进行相同的操作,直到获得没有Extends块的顶级模板.但是也许有更有效的方法?

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?

推荐答案

您可以使用

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 %}

这将导致:

<some_content_from_parent>
<some_content_from_top>
<some_content>

这篇关于从jinja2的父块获取内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆