【问题标题】:Pass urls iteratively into django html template url tag将 url 迭代地传递到 django html 模板 url 标记中
【发布时间】:2021-11-30 21:04:20
【问题描述】:

我有一个主页模板,其中包含指向我想要迭代呈现的许多其他页面的链接:(由于 python 语法,这显然不起作用)

{% for idx, category in enumerate(categories) %}
    <div class="box">
        a href={% url 'category_links[idx]' %}> {{category}}</a>
    div>
{% endfor %}

我有以下网址,从我的角度来看,我也将它们传递给我的模板:

category_links = ['journals', 'proceedings', 'books', 'articles_in_books', 'talks', 'poster', 'habilitations', 'phd_thesis', 'bachelor_master_diploma_thesis', 'lectures', 'conferences', 'calls_and_awards', 'telegrams_and_circulars']

我知道{{forloop.counter0}},但无法正确集成它。

非常感谢您的帮助!

【问题讨论】:

    标签: python django django-templates


    【解决方案1】:

    您可以使用 {{ forloop.counter }} 通过简单地制作自定义模板过滤器来循环槽列表

    IE : 与在 python 中使用 list_object[index] 相同

    templatetags/index.py(在app根目录下创建一个templatetags文件夹)

    from django import template
    register = template.Library()
    
    @register.filter
    def index(list_object, i):
        return list_object[i]
    

    template.html

    {% load index %}
    
    {% for category in categories %}
    {% with forloop.counter0 as i %}
    <div class="box">
        a href='{% url category_links|index:i %}'> {{category}}</a>
    <div>
    {% endwith %}
    {% endfor %}
    

    【讨论】:

    • 我这样做了,但现在我收到错误“NoReverseMatch at / 'category_links|index' 不是注册的命名空间”
    • 我解决了。引号必须在标签之外,像这样&lt;a href="{% url category_links|index:i %}"
    猜你喜欢
    • 1970-01-01
    • 2021-02-15
    • 2017-08-11
    • 2015-02-02
    • 2023-03-31
    • 2011-12-17
    • 2011-03-04
    • 2014-05-13
    • 2021-12-23
    相关资源
    最近更新 更多