【问题标题】:Creating a custom template tag to replace the for loop - Django创建自定义模板标签以替换 for 循环 - Django
【发布时间】:2018-02-13 20:06:56
【问题描述】:

我正在尝试通过为我的 Django Web 应用程序上经常使用的“for 循环”创建自定义模板标签来简化我的代码。我认为这将是一个简单直接的过程,但有些事情不正常......我可以使用一些帮助来发现我的错误。

这是我的代码。 视图.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 %}

模板.html

{% Neurons|term %}

提前感谢您的帮助。

【问题讨论】:

    标签: python django django-template-filters


    【解决方案1】:

    您正在将 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 的新模板:

    templates/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 %}
    

    【讨论】:

    • 维克多,我真的很喜欢你的第二个回复,但我无法让它发挥作用。例如,我设置了一个不同的模板,显示来自 Scientific_terms 模型的数据。如何“包含”动态页面而不仅仅是模板?
    猜你喜欢
    • 2020-09-25
    • 2013-10-29
    • 2018-06-17
    • 1970-01-01
    • 2018-06-19
    • 2015-03-14
    • 2021-09-30
    • 2012-03-28
    • 2021-07-13
    相关资源
    最近更新 更多