【问题标题】:Could not parse the remainder: '{{ list[loop.index0] }}'无法解析剩余部分:'{{ list[loop.index0] }}'
【发布时间】:2019-03-12 00:52:26
【问题描述】:

我遵循了类似线程中的说明,例如:How do you index on a jinja template?

但我的 html 模板无法正常工作,因此整个 django 项目没有响应。

我得到的错误:

模板渲染时出错。

无法解析剩余部分:来自“songs_titles[loop.index0]”的“[loop.index0]”

我的代码如下所示:

{% if converted_files_urls %}
    <p>Titles: {{ songs_titles }}</p>
    {% for n in converted_files_urls %}
        <a href="{{ n }}" download>Download:  {{ songs_titles[loop.index0] }}</a>
        <br/>
    {% endfor %}
{% endif %}

并且 {{ song_titles }} 呈现为列表,所以至少到这里它工作正常。 我做错了什么?

【问题讨论】:

  • 你没有使用 Jinja。这是 Django 模板语言。

标签: python html django templates jinja2


【解决方案1】:

实际上你正在寻找 Jinja,这在 django 上不起作用。

在 django 模板标签中你应该使用forloop.counter0 并且列表索引看起来像

{{songs_titles.1}}

需要在变量中设置计数然后使用它,设置变量你可以使用 -

{% with index=forloop.counter0 %}     

   {{ songs_titles.index}}

{% endwith %}

如果您有任何疑问,可以发表评论。

【讨论】:

  • {{ song_titles.1 }} 有效,{{ forloop.counter0 }} 显示 0、1、3、4 等等,但 {{ song_titles.forloop.counter0 }} 没有显示任何东西
  • 您的解决方案呈现错误:/ 模板呈现期间出错。 'with' 至少需要一个变量赋值
  • 去掉“=”的前后空格,看答案。
【解决方案2】:

我终于通过创建一个自定义模板标签来解决这个问题,如下所示: https://djangosnippets.org/snippets/2740/

但老实说,这是目前最简单的工作解决方案,这很糟糕:/

【讨论】:

    猜你喜欢
    • 2011-04-03
    • 2011-11-06
    • 2013-10-26
    • 2018-03-31
    • 2020-05-10
    • 2017-11-18
    • 1970-01-01
    • 2022-10-05
    • 2011-07-11
    相关资源
    最近更新 更多