jinja icon indicating copy to clipboard operation
jinja copied to clipboard

Support passing arguments to {% include %} tag.

Open miracle2k opened this issue 11 years ago • 4 comments

Would a patch to this effect be merged?

There are some scenarios where you want a have short syntax for useful helper, and using the {% with %} tag is not exactly succinct.

Even the Django guys, reputed to be ultra-conservative about their template language, supports this now.

miracle2k avatar Jun 08 '13 15:06 miracle2k

It strikes me that this could possible be implemented by an Extension that generates with and incude nodes.

miracle2k avatar Jun 08 '13 15:06 miracle2k

There are a couple of ways to do this.

The Django style:

{% include file with key=value %} {# external context is accessible inside included file #}
{% include file with key=value only %} {# external context is not accessible #}

The Twig style (equivalent to the above):

{% include file with { "key" : value } %}
{% include file with { "key" : value } only  %}

The Twig style does provide some additional flexibility:

{% set key = "key1" if case else "key2" %}
{% include file with { key : value } %} {# keys can be dynamically determined #}

{% set args = { "key1" : value1, "key2" : value2 } %}
{% include file with args %} {# variable dictionaries can be passed in #}

Note that this functionality is not achievable using the with tag.

{% with key=value %}
{% include file %} {# the external context is accessible inside of the included file #}
{% include file without context %} {# the value set using with is not accessible #}
{% endwith %}

I've implemented the "Twig style" of this in a separate Jinja extension library, but in order to avoid branching jinja itself, I've had to subclass Template and Environment, I've had to copy and paste a lot of boilerplate, and I've even had to monkey patch a little. Adding the functionality directly to jinja would be much cleaner and involve much less code.

I'd love to put a patch together, if there was some willingness to incorporate the functionality. Is there any possibility that this feature would be accepted into Jinja?

legutierr avatar Jul 28 '15 20:07 legutierr

in jinja 2.9+ you can just wrap the {% include 'file' %} inside a {% with var=val %}{% endwith %}, like so: https://stackoverflow.com/a/32657364

mulllhausen avatar Jan 28 '18 12:01 mulllhausen

I've come across this:

  <!--
    For some reason, the execution of the following tag: {{ active_page }}
    causes the active_page to be kept in "cache" and sent down to the nav.html.
  
    Without the inclusion of active_page above the below nav.html will not receive it.
  -->
  {% include 'nav.html' %}

qaisjp avatar Apr 14 '18 17:04 qaisjp