开发者

Django TemplateTag evaluating to a boolean

开发者 https://www.devze.com 2023-03-06 15:55 出处:网络
Is it possible to create a Django template tag which evaluates to a boolean? Eg, can I do: {% if my_custom_tag %}

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!


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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消