繁体   English   中英

创建自定义模板标签以替换for循环-Django

[英]Creating a custom template tag to replace the for loop - Django

我试图通过为Django Web应用程序上经常使用的“ for循环”创建自定义模板标签来简化代码。 我认为这将是一个简单的简单过程,但是有些方法无法正常工作...我可以使用一些帮助来捕获错误。

这是我的代码。 views.py

 class ArticleView(DetailView):
    model = Articles

    def get_context_data(self, **kwargs):
      context = super(ArticleView, self).get_context_data(**kwargs)
      context['s_terms'] = scientific_terms.objects.all()
      return context

模板标签

@register.filter(name='term')
def term(value):
  {% for term in s_terms %}
        {{ term.short_description }}
  {% endfor %}

template.html

{% Neurons|term %}

预先感谢您的协助。

您正在将Python代码与Django模板语言混合在一起。 模板标记是纯Python代码,因为它们是在Python模块中定义的。 一个有效的例子是:

@register.filter(name='term')
def term(terms):
  output = ''
  for term in terms:
      output = '{0} {1}'.format(output, term.short_description)
  return output

然后,您可以像这样使用它:

{{ s_terms|term }}

也许您想要的只是创建一个可重用的Django模板。

例如,创建一个名为terms.html的新模板:

模板/ terms.html

{% for term in terms %}
    <p>{{ term.short_description }}</p>
{% endfor %}

然后,在另一个模板中,您可以包括以下部分模板:

templates / index.html (名称仅是示例)

{% extends 'base.html' %}

{% block content %}
    <h1>My application</h1>
    {% include 'terms.html' with terms=s_terms %}
{% endblock %}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM