voscausa
voscausa

Reputation: 11706

How to to read a jinja context variable

In my mainline I want to read a variable from the current template context, after the template was rendered. This variable has been "set" bij the template. I can access the variable in a context function, but how to access it in my mainline.

result = template.render({'a' : "value-1" })
# in the template {% set b = "value-2" %}
b = ?

Update : I found a solution in the webapp2 source. The line is :

b = template.module.b

Upvotes: 1

Views: 3883

Answers (2)

voscausa
voscausa

Reputation: 11706

I found out, with the help of the webapp2-extras source, that accessing the current jinja context is possible in the python mainline. See also : class jinja2.Template in the jinja documentation.

Python mainline :

result = template.render({'a' : "value-1" })
# in the template {% set b = "value-2" %}
b = template.module.b

Thanks for your help.

Upvotes: 3

Ski
Ski

Reputation: 14497

I don't recommend you to do what you ask for and instead think of a better solution, anyways here is the hacky-answer:

from jinja2 import Template

class MyImprovedTemplate(Template):
    def render(self, *args, **kwargs):

        # this is copy-pasted from jinja source, context added to return

        vars = dict(*args, **kwargs)
        context = self.new_context(vars)
        try:
            return context, concat(self.root_render_func(context))
        except Exception:
            exc_info = sys.exc_info()
        return context, self.environment.handle_exception(exc_info, True)

>>> t = MyImprovedTemplate('{% set b = 2 %}')
>>> context, s = t.render()
>>> context['b']
'2'

Upvotes: 0

Related Questions