【问题标题】:Django - can't loop through custom templatetagDjango - 无法循环自定义模板标签
【发布时间】:2020-09-25 14:57:23
【问题描述】:

我创建了自定义categories_tag 模板标签,如下所示:

from django import template
register = template.Library()

from ..models import Category

@register.simple_tag(takes_context=True)
def categories_tag(context):
    categories = Category.objects.all()

    return categories

现在想像这样循环遍历这个标签:

<h3>CATEGORIES</h3>
{% for i in categories_tag %}
   <a href="">i</a>
{% endfor %}

但在浏览器中似乎什么都没有。我的代码有什么问题?

【问题讨论】:

  • 这里的上下文是类别,因为您通过类别将对象分配给它所以循环
  • @ngawang13,没用,伙计
  • 我编辑了你的作品。检查它
  • @ngawang13,没有改变任何东西......
  • 导入模型时单点并用我编辑的代码试试

标签: python django django-templates templatetags


【解决方案1】:
{% categories_tag as ct %}
  {% for c in ct %}
    {{ c.name }}
  {% endfor %}

【讨论】:

    猜你喜欢
    • 2021-09-05
    • 2015-03-14
    • 1970-01-01
    • 2021-07-13
    • 2015-01-20
    • 2012-03-15
    • 2017-09-19
    • 2018-06-07
    相关资源
    最近更新 更多