我可以在 Django if 块中使用自定义标签吗?
Can I use a custom tag inside an Django if block?
说我有这个方法:
def is_root_task(self, root=None):
'''Returns true if the task is the root of a series of other tasks'''
super_tasks = self.dependency_sub_task.all()
if not root:
return not super_tasks.exists()
else:
return not super_tasks.exclude(task_id__exact=root.id).exists()
我是这样注册的:
from django import template
from gantt_charts.models import Task
register = template.Library()
register.tag('is_root_task', Task.is_root_task)
如何在 if 块(或类似块)中调用它?例如说我希望它出现在我的页面中:
<ul>
{% for sub_task in task.sub_tasks %}
{% if is_root_task "sub_task" "task" %}
<li >
<p>{{sub_task.title}}</p>
<p>{{sub_task.description}}</p>
</li>
{% endif %}
{% empty %}
<li> No Sub-tasks</li>
{% endfor %}
</ul>
我想将任务变量 (root) 和 sub_task 变量 (self) 传递给 is_root_task,并在 if 块中对其求值。这可能吗?
我已经在 Daniel Roseman
的帮助下解决了这个问题
一切都一样,只是我将 tag
换成了 filter
。我不确定为什么过滤器有效而标签无效,但它们确实有效。
register.tag('is_root_task', Task.is_root_task)
并且在 html 我使用:
{% if sub_task|is_root_task:task %}
从 Django 1.9 开始,您还可以分两步完成此操作,方法是从标签输出中设置一个变量,然后使用 if
.
中的变量
这在简单标记文档的底部进行了描述,网址为:
https://docs.djangoproject.com/en/1.9/howto/custom-template-tags/#simple-tags
在你的情况下它看起来像这样:
{% is_root_task "sub_task" "task" as myflag %}
{% if myflag %}
Do some stuff
{% endif %}
如果您重复使用 myflag
,这种处理方式很好,可以避免重复调用标签的开销。
说我有这个方法:
def is_root_task(self, root=None):
'''Returns true if the task is the root of a series of other tasks'''
super_tasks = self.dependency_sub_task.all()
if not root:
return not super_tasks.exists()
else:
return not super_tasks.exclude(task_id__exact=root.id).exists()
我是这样注册的:
from django import template
from gantt_charts.models import Task
register = template.Library()
register.tag('is_root_task', Task.is_root_task)
如何在 if 块(或类似块)中调用它?例如说我希望它出现在我的页面中:
<ul>
{% for sub_task in task.sub_tasks %}
{% if is_root_task "sub_task" "task" %}
<li >
<p>{{sub_task.title}}</p>
<p>{{sub_task.description}}</p>
</li>
{% endif %}
{% empty %}
<li> No Sub-tasks</li>
{% endfor %}
</ul>
我想将任务变量 (root) 和 sub_task 变量 (self) 传递给 is_root_task,并在 if 块中对其求值。这可能吗?
我已经在 Daniel Roseman
的帮助下解决了这个问题一切都一样,只是我将 tag
换成了 filter
。我不确定为什么过滤器有效而标签无效,但它们确实有效。
register.tag('is_root_task', Task.is_root_task)
并且在 html 我使用:
{% if sub_task|is_root_task:task %}
从 Django 1.9 开始,您还可以分两步完成此操作,方法是从标签输出中设置一个变量,然后使用 if
.
这在简单标记文档的底部进行了描述,网址为: https://docs.djangoproject.com/en/1.9/howto/custom-template-tags/#simple-tags
在你的情况下它看起来像这样:
{% is_root_task "sub_task" "task" as myflag %}
{% if myflag %}
Do some stuff
{% endif %}
如果您重复使用 myflag
,这种处理方式很好,可以避免重复调用标签的开销。