Reputation:
I want to use Jinja2 to store a template as a string variable in python instead of rendering it as a file. How would I go about doing this ?
For example using f-strings I'd do :
template = f""" This is a {foo}"""
Unfortunately f-strings don't suit my needs hence I wanted to try out Jinja2.
Edit : Requirement
cars = {
'tesla': {
'cost': '34000',
'length': '185',
'range': '220',
},
'chevy': {
'cost': '37000',
'length': '134',
'range': '238',
}
I would like to take the values from this dictionary, insert it into template and store it as a string to be used later.
I tried using the below code but I get an invalid syntax error.
template1 = Template("""Tesla
Cost : {{ cars.tesla.cost }}""")
template2 = template1.render()
# Expected Output
print(template2)
Tesla
Cost : 34000
Upvotes: 3
Views: 13627
Reputation: 5463
As its not clear what your requirement is, a simple way to store a jinja2 template in a variable is available through the Template
class. The following example from the jinja2 docs shows how you can do it:
from jinja2 import Template
template = Template('Hello {{ name }}!')
If I print template
, it shows a Template
object stored in memory:
print(template)
#Output
<Template memory:2ea4e10>
You can pass a custom name to the render()
and print the template with the value of name
:
print(template.render(name='John Wick'))
#Output:
Hello John Wick!
A slightly more complex template can be stored in a simple variable and then passed to Template
:
jinja_string = """<title>{{title}}</title>
<ul>
{% for user in users %}
<li>{{ user }}</li>
{% endfor %}
</ul>"""
template = Template(jinja_string)
users = ["John", "Sam", "Joe"]
print(template.render(title="Users", users=users))
#Output:
<title>Users</title>
<ul>
<li>John</li>
<li>Sam</li>
<li>Joe</li>
</ul>
For the expected output template:
jinja_string = """{{title}}:
{% for car,value in cars.items() %}
Car: {{ car }}
Cost: {{value['cost']}}
Length: {{value['length']}}
Range: {{value['range']}}
{% endfor %}
"""
template = Template(jinja_string)
cars = {
'tesla': {
'cost': '34000',
'length': '185',
'range': '220',
},
'chevy': {
'cost': '37000',
'length': '134',
'range': '238',
}
}
print(template.render(title="Cars", cars=cars))
#Output:
Cars:
Car: tesla
Cost: 34000
Length: 185
Range: 220
Car: chevy
Cost: 37000
Length: 134
Range: 238
Upvotes: 4