inja icon indicating copy to clipboard operation
inja copied to clipboard

Feature Request: provide different data context for included template

Open kiddliu opened this issue 2 years ago • 1 comments

Problem I'm Trying To Solve

I'd like to pass a variable as the data context of the included template, so a huge template can be split into more modularized sub-templates.

Current Solution

I can only have a huge template with complicated JSON as the only data context.

Requested Solution

It would be very convenient if I could have the following:

#include <string>

#include "data.h"
#include "util.h"

## for namespace in namespaces
    {{ include “namespace-template”:namespace }}
## endfor

in which "namespace-template" refers to the sub-template which handles the namespace only, and :namespace is the provided data context, so don't have to nest loops/conditions in a single template.

kiddliu avatar Nov 02 '21 08:11 kiddliu

I've found Twig to handle this in a very elegant and idiomatic manner:

Included templates have access to the variables of the active context. If you are using the filesystem loader, the templates are looked for in the paths defined by it. You can add additional variables by passing them after the with keyword:

{# template.html will have access to the variables from the current context and the additional ones provided #}
{% include 'template.html' with {'foo': 'bar'} %}

{% set vars = {'foo': 'bar'} %}
{% include 'template.html' with vars %}

You can disable access to the context by appending the only keyword:

{# only the foo variable will be accessible #}
{% include 'template.html' with {'foo': 'bar'} only %}

{# no variables will be accessible #}
{% include 'template.html' only %}

I don't know how doable it is, and it's perhaps best to stay close to Jinja. Just 2 cents, because the with/only pattern is really neat.

Goutte avatar Jun 11 '22 23:06 Goutte