Jinja2 templating with components? blocks? templates?
Asked Answered
G

2

3

A little question to jinja2 templating: I want to create a reusable template to include and then overwrite blocks. Macros do not let me write junks of HTML easily as parameters do they? Say I want to reuse an include several times and am using BIG junks of HTML in blocks that I want to dynamically assign how would I do it?

certainly not with macros I guess, or am I wrong?

{% render_foo('bar',2) %} is fine

{% render_foo('<table><tr><th>something</th><th>somethingelse</th></tr><tbody><tr>....etc') %} is not fine any more is it

"what do you really want to do?"

yes, what I told you, I have a way I create containers for my data. The container is ALWAYS the same. The content is completely different on each usage. Once a table. Once a bootstrap component. Once a form.

The surrounding elements are always the same

to reproduce the simple error this is what I did:

 {% include 'full_section.html' %}
  {% block fullsection %} <table><tr><th>something</th><th>somethingelse</th></tr><tbody><tr>....etc{% endblock %}

  {% include 'full_section.html' %}
  {% block fullsection %} <form>//some cool LONG big form </form>{% endblock %}

full_section.html contents just for completeness, it is a lot more complex in reality

<div class="my_cool_full_section">
{% block full_section %}{% endblock %}
</div>

TemplateAssertionError: block 'fullsection' defined twice

Gluttonous answered 15/7, 2017 at 0:0 Comment(0)
G
6

I found the answer well hidden in the jinja2 docs

http://jinja.pocoo.org/docs/2.9/templates/#block-assignments

so you use a macro and a block assignment e.g. like this:

{% set section_content %}
<table><tr><td>etc</td> <td>etc</td> <td>etc</td></tr></table>
<table><tr><td>etc</td> <td>etc</td> <td>etc</td></tr></table>
<table><tr><td>etc</td> <td>etc</td> <td>etc</td></tr></table>
  {% endset %}
  {{  render_full_size_section(section_content)  }}


  {% set section_content %}
  aaaaaaaaaaa
    {% endset %}
    {{  render_full_size_section(section_content)  }}

wonder what they were doing pre 2.8... dark dark middle age

then in the macro:

{% macro render_full_size_section(content) %}
<div class="mycoolsection">
  {{ content | safe }}
</div>
{% endmacro %}
Gluttonous answered 15/7, 2017 at 0:19 Comment(0)
H
0

Use the jinja call tag to nest macros with other macros or html content

{% call render_dialog('Hello World') %}
    This is a simple dialog rendered by using a macro and
    a call block.
{% endcall %}

alternatively you can set HTML to a set tag block and pass it as a macro prop

{% set navigation_html %}
    <li><a href="/">Index</a>
    <li><a href="/downloads">Downloads</a>
{% endset %}

{{ my_macro(navigation_html) }}
Holozoic answered 11/4, 2024 at 0:28 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.