Search code examples
jinja2

Get a variable value from it's name in a Jinja


How do get the value of a variable (passed as a named argument to Flask's make_response) from it's name in a Jinja template?

Currently I use

{% set value = self._TemplateReference__context.resolve(arg_name) %}

but this feels like a low level kludge. There must be some other more idiomatic way.


Solution

  • In cases where you have access to the backend code, the general way to handle cases like this where Jinja lacks support for something, especially if it involves access to things at the backend is to use a context_processor which creates a dictionary of values or functions that are then available in Jinja templates through the provided keys.

    If you further want a function provided in this way to have access to the template context, decorate it with Jinja's pass_context, to pass the context as the first argument to the decorated function:

    from flask import Flask
    from jinja2 import contextfunction
    
    app = Flask(__name__)
    
    # ...
    
    @app.context_processor
    def inject_template_utilities():
        company = "My Company"
        @pass_context
        def get_render_var(ctx, name):
            return ctx.get(name)
        return {'get_render_var': get_render_var, 'company': company}
    

    Then in your template instead of

    {% set value = self._TemplateReference__context.resolve(arg_name) %}
    

    you can use

    {% set value = get_render_var(arg_name) %}