Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get content from parent block in 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

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?

like image 702
Sergey Troinin Avatar asked Jun 27 '15 21:06

Sergey Troinin


People also ask

What is block content in Jinja?

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.

What is the difference between Jinja and Jinja2?

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.

What is Autoescape in Jinja2?

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.


1 Answers

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>
like image 120
dirn Avatar answered Oct 25 '22 22:10

dirn