Search code examples
jinja2

Dynamically referencing a variable in jinja2?


Is it possible to dynamically reference a variable in jinja2?

{%- set varA = 5 -%}
{%- set varB = 10 -%}
{%- set input = 'A' -%}

{%- set output = 'var' + input -%}
Output: {{ output }}

{# I get "Output: varA", but I would like to get "Output: 5" #}

I can do it with an if/else statement, but want to see if i can do it dynamically, in case i have inputs A-Z, for example.

{%- if input == 'A' -%}
  {%- set output = varA -%}
{%- else -%}
  {%- set output = varB -%}
{%- endif -%}
Output: {{ output }}

I thought a macro might help, but seems to return as a string:

{%- macro doit(input) -%}
  var{{input}}
{%- endmacro -%}

{%- set output = doit(input) -%}
Output: {{ output }}
{# Returns "Output: varA" #}

Solution

  • try that:

    template = """
        {%- set varA = 5 -%}
        {%- set input = 'A' -%}
        {%- set output = 'var' ~ input  -%}
        Output: {{ self._TemplateReference__context.resolve(output) }}
    """
    temp = jinja2.Template(template)
    result = temp.render()
    print(result)
    

    result:

    Output: 5