Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support passing arguments to {% include %} tag. #241

Open
miracle2k opened this issue Jun 8, 2013 · 4 comments
Open

Support passing arguments to {% include %} tag. #241

miracle2k opened this issue Jun 8, 2013 · 4 comments

Comments

@miracle2k
Copy link

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
Copy link
Author

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

@legutierr
Copy link

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?

@mulllhausen
Copy link

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

@qaisjp

This comment has been minimized.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants