Search code examples
djangojinja2

Jinja2 templating with components? blocks? templates?


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


Solution

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