nowox
nowox

Reputation: 29106

Accessing a numeric key in jinja2

This code doesn't work:

#!/usr/bin/python
from jinja2 import Template
t = Template("Hello {{ 42.baz }}!")
print t.render({42:{'baz':'World'}})

It displays Hello ! and not Hello World!

Is it possible with to access a numeric key as is it possible to declare a dict with numeric keys?

Notice that {'42':{'baz':'World'}} is not a solution

Upvotes: 2

Views: 438

Answers (1)

Mariusz Jamro
Mariusz Jamro

Reputation: 31653

Numbers and strings are evaluated as literals, and you cannot force Jinja to treat them as variable names because of how the Jinja's name patterns work. So {{ 42 }} means 42 and not variable named 42.

The simplest solution would be to do like that:

from jinja2 import Template
t = Template("Hello {{ vars[42].baz }}!")
print t.render(vars={42:{'baz':'World'}})

The vars is just a name, it can be whatever you want.

Upvotes: 3

Related Questions