Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save the result of a comparison using Django's 'with' template tag?

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?

like image 808
trikoder_beta Avatar asked Jun 19 '15 08:06

trikoder_beta


People also ask

What is the use of template tag in Django?

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.

How do you pass variables from Django view to a template?

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.

How do I create a custom template tag?

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.


1 Answers

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

like image 119
igolkotek Avatar answered Sep 28 '22 11:09

igolkotek