简体   繁体   English

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

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

I am trying to simplify my code by creating a custom template tag for a 'for loop' that use frequently on my Django web application. 我试图通过为Django Web应用程序上经常使用的“ for循环”创建自定义模板标签来简化代码。 I thought it would be a simple straight process, but something isn't working right... I can use some assistance in catching my error. 我认为这将是一个简单的简单过程,但是有些方法无法正常工作...我可以使用一些帮助来捕获错误。

Here is my code. 这是我的代码。 views.py 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

template tag 模板标签

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

template.html template.html

{% Neurons|term %}

Thank you for your assistance, in advance. 预先感谢您的协助。

You are mixing Python code with the Django Template Language. 您正在将Python代码与Django模板语言混合在一起。 The template tags are plain Python code, as they are defined inside a Python module. 模板标记是纯Python代码,因为它们是在Python模块中定义的。 A working example would be: 一个有效的例子是:

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

Then you could use it like this: 然后,您可以像这样使用它:

{{ s_terms|term }}

Maybe what you want is simply to create a reusable Django template. 也许您想要的只是创建一个可重用的Django模板。

For example, create a new template named terms.html : 例如,创建一个名为terms.html的新模板:

templates/terms.html 模板/ terms.html

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

Then, in another template, you could include this partial template: 然后,在另一个模板中,您可以包括以下部分模板:

templates/index.html (name is just an example) 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