10
votes

My Jinja top-level context has variables defined in sequence like foo_0, foo_1, etc.

I'd like to be able to access those variables dynamically by generating strings with code like "foo_" + str(0).

If effect, I want to do something like {{ eval("foo_0") }} in my Jinja template, and access those variables in sequence.

Is this possible?

Note: I'm using a cloud service I don't control (which provides Jinja templating), so:

  • I can't use data structures in the Jinja context (all variable values must be strings).
  • I can't customize the Jinja runtime environment or add filters. But it would be helpful to know if this can be solved by adding a custom filter.
1
This problem is really irking me! The "all variables must be strings" is really what's getting to me. If you could just pass in one function with the contextfunction decorator, this would be simple!Olly F-G

1 Answers

5
votes

I wasn't able to find a standard/documented way to do this but through poking around:

In [30]: Template("{{ self._TemplateReference__context.resolve('foo_0')  }}").render(foo_0='this_is_foo_0', foo_1='this_is_foo_1')
Out[30]: 'this_is_foo_0'