Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically get a variable (from a string) in Jinja

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.
like image 282
Max Wallace Avatar asked Sep 06 '16 22:09

Max Wallace


1 Answers

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'
like image 123
Dan Frank Avatar answered Sep 29 '22 14:09

Dan Frank