Reputation: 129
I have used jinja2 to generate a json template. The json template is generated as expected. However, How do I make some parameters optional. For instance, In the below template sam, uri_2 and uri_3
are optional. When I don't pass the values for them in template.render
, I don't want those parameters returned in the template. Currently, empty values are returned for those parameters.
from jinja2 import Template
template = Template('''
{
"start": "{{start}}",
"end": "{{end}}",
"sam": "{{sam}}",
"res": "{{res}}",
"uris":
[
"{{uri_1}}",
"{{uri_2}}",
"{{uri_3}}"
]
}
''')
payload = template.render(start=1560009000, end=1560009000, res=3, uri="abc.com")
output:
{"end": "1540995788", "res": "3", "sam": "", "start": "1540390988", "uris": ["abc.com", "", ""]}
Upvotes: 3
Views: 7042
Reputation: 1435
In terms of parameters not passed at all (e.g. sam
in your example) then
{% if sam %}
"sam" : "{{ sam }}"
{% else %}
{%endif %}
You should probably pass your uri
values as a list then do something like this in the template:
"uris":
[
{% for uri in uris %}
"{{ uri }}"
{% endfor %}
]
If there are no uri
values and you are not passing a list to render.template
then you could omit the "uris"
tag completely in a similar fashion to sam
.
Upvotes: 9