如何在django中编写更好的模板标签 [英] How to write better template tags in django
问题描述
我已经看到如何编写模板标签,根据这样的模板设置上下文变量
{% my_template_tag'blah'as my_context_variable%}
但是我想要这样做:由于组
和用户
都设置在$ p
视图中的上下文
{%is_in_group group user as is_member%}
{%if is_member% }
#....做东西....
{%endif%}
或理想情况如下:
{%if is_in_group group user%}
#... 。
{%end if%}
显然, code> is_member 在视图中 - 但这只是一个例子,很高兴知道如何做这样的事情!
Evgeny对smart_if模板标签有个好主意。但是,如果这样做不起作用,您可能会发现自定义过滤器比较容易编写。如下:
@ register.filter
def is_in(obj,val):
return val is在obj
,你会这样使用:
{%if user | is_in:group.users%}
I've seen how I can write template tags that set a context variable based on a template like this
{% my_template_tag 'blah' as my_context_variable %}
But I'd like to be able to do this:
given that both group
and user
are set in the context in the view
{% is_in_group group user as is_member %}
{% if is_member %}
#.... do stuff ....
{% endif %}
or ideally something like this:
{% if is_in_group group user %}
# ....
{% end if %}
Obviously the other way round is to just set is_member
in the view - but this is just an example and would be good to know how to do something like this anyway!
Evgeny has a good idea with the smart_if template tag. However, if that doesn't work, you will probably find that a custom filter is easier to write for this sort of comparison. Something like:
@register.filter
def is_in(obj, val):
return val is in obj
and you would use it like this:
{% if user|is_in:group.users %}
这篇关于如何在django中编写更好的模板标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!