Home > Software engineering >  jinja2 in python and rendering
jinja2 in python and rendering

Time:12-03

I am unable to decipher the error here. Can any one help ?

from jinja2 import Template

prefixes  = {
    "10.0.0.0/24" : {
        "description": "Corporate NAS",
        "region": "Europe",
        "site": "Telehouse-West"
    }
}

template = """
Details for 10.0.0.0/24 prefix:
 Description: {{ prefixes['10.0.0.0/24'].description }}
 Region: {{ prefixes['10.0.0.0/24'].region }}
 Site: {{ prefixes['10.0.0.0/24'].site }}
"""

j2 = Template(template)
print(j2.render(prefixes))

Error:

  File "c:\Users\verma\Documents\Python\jinja\jinja1.py", line 19, in <module>
    print(j2.render(prefixes))
  File "C:\Users\verma\AppData\Roaming\Python\Python310\site-packages\jinja2\environment.py", line 1301, in render
    self.environment.handle_exception()
  File "C:\Users\verma\AppData\Roaming\Python\Python310\site-packages\jinja2\environment.py", line 936, in handle_exception
    raise rewrite_traceback_stack(source=source)
  File "<template>", line 3, in top-level template code
  File "C:\Users\verma\AppData\Roaming\Python\Python310\site-packages\jinja2\environment.py", line 466, in getitem
    return obj[argument]
jinja2.exceptions.UndefinedError: 'prefixes' is undefined

I was expecting the jinja2 rendering to work.

CodePudding user response:

render uses keyword arguments. replace print(j2.render(prefixes)) with print(j2.render(prefixes=prefixes)) and it should work.

CodePudding user response:

If you want to pass prefixes as a positional argument, you should change the prefixes dictionary to be:

prefixes = {
    "prefixes": {
        "10.0.0.0/24": {
            "description": "Corporate NAS",
            "region": "Europe",
            "site": "Telehouse-West"
        }
    }
}

CodePudding user response:

The error message indicates that the prefixes variable is not defined when the Jinja2 template is rendered. This is likely because the prefixes variable is defined within the scope of the script, but it is not passed to the render() method as a variable.

To fix this, you can pass the prefixes variable as a keyword argument to the render() method, like this:


print(j2.render(prefixes=prefixes))

This will make the prefixes variables available to the Jinja2 template, and the rendering should work as expected.

  • Related