Search code examples
pythonjinja2

Can you create components in Flask/Jinja to insert in various templates


Let's say I make a really cool search box layout that I'd like to reuse

eg.

<div class='someClass'>
    <input class='fancyInput'>
</div>

Is it possible to reuse that snippet in other templates in the same way I can extend upon a template, but instead "import" a snippet so to speak. Like the reserve of `{% extend %}

I'd like to have html blocks that I can reuse but insert into different areas depending on the page.

Currently every time I want to use that block of HTML I have to hard code it in.

here's a pseudo html/jinja example

The snippet

{% component fancyInput %} # not real jinja

<div class='someClass'>
    <input class='fancyInput'>
</div>

{% endcomponent %}

Then lets say on a random page somewhere

<html>
<body>
    <div class='container'><p>Some text!</p></div>
    {% import component fancyInput}
</body>
</html>

The rendered HTML would be

<html>
<body>
    <div class='container'>
        <p>Some text!</p>
    </div>
    <div class='someClass'>
        <input class='fancyInput'>
    </div>
</body>
</html>

Solution

  • Jinja2 uses macros. Once a Macro is defined, it can be called on to render elements.

    So if you define a macro in a template like:

      {% macro newComponent(text) -%}
          <div class='container'><p>{{text}}</p></div>
      {%- endmacro %}
    

    Then it can be called on in any file with

    {{ newComponent('Insert Text') }}
    

    Here is a link to the documentation

    Also Stack Overflow post on macros Parameterized reusable blocks with Jinja2 (Flask) templating engine