yee379
yee379

Reputation: 6752

Referencing jinja2 variable from a variable

I want to be able to apply DRY and not have to repeat myself when building my jinja2 template. So I would like to be able to reference a variable within the jinja2 template from a dynamically constructed variable name, eg:

{% for a in [ 'a', 'b', 'c'] %}
{% set name = a + "_name" %}
{% set value = {{ name }} %}
hello there {{ value }}
{% endfor %}

where my input variables into jinja would be

a_name = 1
b_name = 2
c_name = 3

and I the result would be

hello there 1
hello there 2
hello there 3

is this possible?

I know i would just pass in a datastructure into jinja2 to do something similar, but I am not at liberty to modify what goes into the template.

Upvotes: 2

Views: 2767

Answers (1)

yee379
yee379

Reputation: 6752

i got the answer from here

basically, define a contextfunction and reference it within the jinja code:

from jinja2 import Environment, FileSystemLoader, contextfunction

j2_env = Environment( loader=FileSystemLoader(directory), trim_blocks=False )
this_template = j2_env.get_template( """
    {% for i in [ 'a', 'b', 'c'] %}
    hello there {{ context()[i+"_name"] }}
    {% endfor %}
""" )

@contextfunction
def get_context(c):
  return c
this_template.globals['context'] = get_context
this_template.render( **{ 'a_name': 1, 'b_name': 2, 'c_name': 3 } )

Upvotes: 0

Related Questions