zjm*_*126 38 django django-templates
使用此代码:
{% for o in [1,2,3] %}
<div class="{% cycle 'row1' 'row2' %}">
{% cycle 'row1' 'row2' %}
</div>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
我得到一个TemplateSyntaxError:
Could not parse the remainder: '[1,2,3]' from '[1,2,3]'
Run Code Online (Sandbox Code Playgroud)
有没有办法在模板中构建列表?
Zul*_*ulu 57
我们可以在str对象上使用split方法:
page.html:
{% with '1 2 3' as list %}
{% for i in list.split %}
{{ i }}<br>
{% endfor %}
{% endwith %}
Run Code Online (Sandbox Code Playgroud)
结果:
1
2
3
Run Code Online (Sandbox Code Playgroud)
Dom*_*ger 27
你可以通过巧妙地使用make_list过滤器来做到这一点,但这可能是一个坏主意:
{% for o in "123"|make_list %}
<div class="{% cycle 'row1' 'row2' %}">
{% cycle 'row1' 'row2' %}
</div>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
ps你似乎没有在o任何地方使用,所以我不确定你要做什么.
rab*_*ron 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
Run Code Online (Sandbox Code Playgroud)
在模板中使用它:
{% load your_template_tag_file %}
{% to_list 1 2 3 4 5 "yes" as my_list %}
{% for i in my_list %}
{{ i }}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
参考这里: Django赋值标签
Ale*_*ore 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>
Run Code Online (Sandbox Code Playgroud)
其中按钮之间的区别仅限于按钮的文本(模态,上面自己的行)以及与按钮相关的内容,我们假设它由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 %}
Run Code Online (Sandbox Code Playgroud)
现在,在这种特殊情况下,按钮会为某些相关数据网格添加功能,因此按钮名称也可以从django模型源数据中动态填充,但我现在不在我的设计的那个阶段,并且你可以看到这种功能在哪里可以维持DRY.
| 归档时间: |
|
| 查看次数: |
41947 次 |
| 最近记录: |