Pur*_*ret 1 django django-templates
假设我有这个方法:
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()
Run Code Online (Sandbox Code Playgroud)
我这样注册:
from django import template
from gantt_charts.models import Task
register = template.Library()
register.tag('is_root_task', Task.is_root_task)
Run Code Online (Sandbox Code Playgroud)
如何在 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>
Run Code Online (Sandbox Code Playgroud)
我想将任务变量(root)和 sub_task 变量(self)传递给 is_root_task,并在 if 块内对其进行评估。那可能吗?
从 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 %}
Run Code Online (Sandbox Code Playgroud)
如果您重复使用 , 这种做法很好myflag,可以避免重复调用标记的开销。
| 归档时间: |
|
| 查看次数: |
1213 次 |
| 最近记录: |