我可以在Django if块中使用自定义标签吗?

时间:2015-01-23 16:47:53

标签: 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()

我这样注册:

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块内部对其进行评估。这可能吗?

2 个答案:

答案 0 :(得分:2)

从Django 1.9开始,你也可以通过设置标签输出中的变量,然后使用public class MainApp { public MainApp(TextFileWriter textFileWriter){ this.textFileWriter = textFileWriter; } public MainApp(){ } @Autowired TextFileWriter textFileWriter; public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext( "/META-INF/spring/application-context.xml"); System.out.println("Context loaded..."); TextFileWriter textFileWriter = (TextFileWriter ) context.getBean("textFileWriter"); MainApp obj=new MainApp(textFileWriter ); obj.someMethod(); context.registerShutdownHook(); } private void someMethod() { try { textFileWriter.write("hi there"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } 内的变量,分2步完成。

这是在Simple Tag文档底部描述的: https://docs.djangoproject.com/en/1.9/howto/custom-template-tags/#simple-tags

在你的情况下,它看起来像这样:

if

如果您反复使用{% is_root_task "sub_task" "task" as myflag %} {% if myflag %} Do some stuff {% endif %} ,这种做法很好,以避免重复调用标记的开销。

答案 1 :(得分:0)

我在Daniel Roseman

的帮助下解决了这个问题

除了我为tag换出filter之外,一切都是一样的。我不确定为什么过滤器工作而标签没有,但他们确实如此。

register.tag('is_root_task', Task.is_root_task)

在我使用的HTML中:

{% if sub_task|is_root_task:task %}