在Django模板中构建一个列表

问题描述 投票:35回答:7

使用此代码:

{% for o in [1,2,3] %}
    <div class="{% cycle 'row1' 'row2' %}">
        {% cycle 'row1' 'row2' %}
    </div>
{% endfor %}

我得到一个TemplateSyntaxError

Could not parse the remainder: '[1,2,3]' from '[1,2,3]'

有没有办法在模板中构建列表?

django django-templates
7个回答
26
投票

你可以通过巧妙地使用make_list过滤器来做到这一点,但这可能是一个坏主意:

{% for o in "123"|make_list %}
    <div class="{% cycle 'row1' 'row2' %}">
        {% cycle 'row1' 'row2' %}
    </div>
{% endfor %}

附:你似乎没有在任何地方使用o,所以我不确定你要做什么。


55
投票

我们可以在str对象上使用split方法:

page.html:

{% with '1 2 3' as list %}
  {% for i in list.split %}
    {{ i }}<br>
  {% endfor %}
{% endwith %}

结果:

1
2
3

13
投票

现在可能有点太晚了。我制作了这个模板标签来实现这个目标。

from django import template
register = template.Library()

# use @register.assignment_tag
# only when you're working with django version lower than 1.9
@register.simple_tag
def to_list(*args):
    return args

在模板中使用它:

{% load your_template_tag_file %}
{% to_list 1 2 3 4 5 "yes" as my_list %}
{% for i in my_list %}
    {{ i }}
{% endfor %}

参考这里:Django assignment tags


10
投票

这里的其他答案看起来像票(至少是我想要的),所以我会提供一个答案,说明为什么你可能想做这样的事情(也许对我的案子有一个比给出的更好的答案) :

我遇到了这个问题,寻找一种使用Bootstrap构建3个非常相似但不完全相同的按钮的方法。一个按钮可能看起来像

<div class="btn-group">
  <a class="btn btn-primary dropdown-toggle" data-toggle="dropdown" href="#">
    Modality
    <span class="caret"></span>
  </a>
  <ul class="dropdown-menu" id="Modality">
    <li><a href="#">Action</a></li>
  </ul>
</div>

其中按钮之间的区别仅限于按钮的文本(模态,上面自己的行)以及与按钮相关的内容,我们假设它由JS动态填充(引用id =“模态”) 。

如果我需要制作其中的10个,复制/粘贴HTML似乎是愚蠢和乏味的,特别是如果我想在事后更改关于我的按钮的任何内容(比如将它们全部拆分下拉)并且它反对DRY。

所以,相反,在模板中,我可以做类似的事情

{% with 'Modality Otherbutton Thirdbutton' as list %}
  {% for i in list.split %}
    <!-- copy/paste above code with Modality replaced by {{ i }} -->
  {% endfor %}
{% endwith %}

现在,在这种特殊情况下,按钮会为某些相关数据网格添加功能,因此按钮名称也可以从django模型源数据中动态填充,但我现在不在我的设计的那个阶段,并且你可以看到这种功能在哪里可以维持DRY。


6
投票

最简单的是做

{% for x in "123" %}

2
投票

drodger是正确的,你不能在刻意瘫痪的Django模板语言中做到这一点。当您调用模板或尝试像expr这样的模板标记时,可以将列表作为上下文变量传入。然后你可以说{% expr [1,2,3] as my_list %}然后在你的for循环中使用my_list


0
投票

这可能是一种灵感。使用内置的过滤器qazxsw poi。

add

官方规格,{{ first|add:second }} first is [1, 2, 3] and second is [4, 5, 6], then the output will be [1, 2, 3, 4, 5, 6]. This filter will first try to coerce both values to integers. If this fails, it'll attempt to add the values together anyway. This will work on some data types (strings, list, etc.) and fail on others. If it fails, the result will be an empty string.

© www.soinside.com 2019 - 2024. All rights reserved.