Django TemplateTag evaluating to a boolean

烈酒焚心 提交于 2019-12-08 16:53:47

问题


Is it possible to create a Django template tag which evaluates to a boolean?

Eg, can I do:

{% if my_custom_tag %}
    ..
{% else %}
    ..
{% endif %}

At the moment I've written it as an as tag, which works fine like this:

{% my_custom_tag as var_storing_result %}

But I was just curious if I could do it the other way as I think it'd be nicer if I didn't have to assign the result to a variable first.

Thanks!


回答1:


You'd have to write a custom {% if %} tag of some sort to handle that. In my opinion, it's best to use what you already have in place. It works well, and is easy for any other developers to figure out what's going on.




回答2:


One alternative might be to define a custom filter that returns a boolean:

{% if my_variable|my_custom_boolean_filter %}

but that will only work if your tag depends on some other template variable.




回答3:


Actually.. what you can do is register tag as assignment_tag instead of simple_tag Then in your template you can just do {% my_custom_tag as var_storing_result %} one time and then regular if blocks where ever you want to evaluate the boolean. Super useful! For example

Template Tag

def my_custom_boolean_filter:
    return True

register.assignment_tag(my_custom_boolean_filter)

Template

{% my_custom_boolean_filter as my_custom_boolean_filter %}


{% if my_custom_boolean_filter %}
    <p>Everything is awesome!</p>
{% endif %}

Assignment Tag Official Doc



来源:https://stackoverflow.com/questions/6047959/django-templatetag-evaluating-to-a-boolean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!