Dread
Dread

Reputation: 861

Jinja2 - pass variable to render

I'm trying to define a variable named "body" and then pass it to the render statement for a Jinja2 template. If I define the variable on a separate line and then use the render statement with just the variable name, I get an error.

Example code:

from jinja2 import Environment, FileSystemLoader
import os

THIS_DIR = os.path.dirname(os.path.abspath(__file__))

env = Environment(loader=FileSystemLoader(THIS_DIR),
                         trim_blocks=True)
template =  env.get_template('test_template.html')
body = "test"
html_str = template.render(body)

Error for the above code:

ValueError: dictionary update sequence element #0 has length 1; 2 is required

It works if I define the variable within the parenthesis of the render statement.

This works but it isn't what I want to do:

from jinja2 import Environment, FileSystemLoader
import os

THIS_DIR = os.path.dirname(os.path.abspath(__file__))

env = Environment(loader=FileSystemLoader(THIS_DIR),
                         trim_blocks=True)
template =  env.get_template('test_template.html')
html_str = template.render(body="test")

Upvotes: 0

Views: 5361

Answers (2)

Gelineau
Gelineau

Reputation: 2090

You can use:

html_str = template(body=body)

The bodyleft to the equal sign is the name of the variable as it will be called inside the template. The bodyon the right of the equal sign is the name of the variable inside the python code

Upvotes: 0

Shivam Singh
Shivam Singh

Reputation: 1624

You should use

body = {"body":"test"}
html_str = template.render(body)

Upvotes: 2

Related Questions