Reputation: 1438
I wonder if it's possible to partial render Django template. Let me make it clear what I want, please check this out (this is in django shell python manage.py shell
, not in basic python shell):
from django.template import Context, Template
t = Template('{{var1}} - {{var2}}, {% if var2 %} {{var3}} {% endif %}')
t.render(Context({'var1': 'test'}))
output:
'test - , '
But I wonder, if it's possible to render only passed variables, so my desired output is
'test - {{var2}}, {% if var2 %} {{var3}} {% endif %}'
I want to get it, because I didn't pass var2
and my main goal here is to render the template in few steps, not in one step. I know there is a string_if_invalid
setting, but it's only for debug purpose.
Upvotes: 1
Views: 518
Reputation: 29957
This is is not possible out of the box. Evaluation of variables happens while rendering template nodes, so each template tag would have to support this.
For really simple templates, like {{var1}} - {{var2}}
, you could create a custom Context
subclass that returns {{ key }}
for any missing variables. But this approach would not work as intended as soon as you use filters or use a variable in a tag, like in your example.
Upvotes: 2