I would like to create new variable in django template, which will have a value of comparison
obj.site.profile.default_role == obj
Unfortunately none of this code works:
{% with obj.site.profile.default_role==obj as default %}{% endwith %}
{% with default=obj.site.profile.default_role==obj %}{% endwith %}
What is the proper syntax?
The template tags are a way of telling Django that here comes something else than plain HTML. The template tags allows us to to do some programming on the server before sending HTML to the client.
And this is rather simple, because Django has built-in template modules that makes a transfer easy. Basically you just take the variable from views.py and enclose it within curly braces {{ }} in the template file.
Create a custom template tagUnder the application directory, create the templatetags package (it should contain the __init__.py file). For example, Django/DjangoApp/templatetags. In the templatetags package, create a . py file, for example my_custom_tags, and add some code to it to declare a custom tag.
with
can take just a "plain" context variable.
You could try assignment-tags instead, passing your params to it.
@register.assignment_tag
def boolean_tag(default_role, obj):
return default_role == obj
and in the template
{% boolean_tag obj.site.profile.default_role obj as my_check %}
This solution is good if variable is used in one template block (like the case of yours, when you try using with
). If you need variable in several page blocks, adding it to page context with include
tag is better
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With