如何在Django模板中将我的单选按钮像2一样对齐


{% for t in test%}
<label>
<input type="radio" name="radio" checked/>
<span class="choice">{{t.choice}}</span>
</label>
{% endfor %}

这是我打印n个单选按钮的代码,我想将它们格式化为2行,但这很困难,因为我们有一个循环。我该怎么做才能在一行中显示2个单选按钮。

有一种方法可以通过更新视图和模板来解决这个问题。在视图中,将test转换为2元组列表,如下所示:

test = [(a0, a1), (b0, b1), (c0, c1), ...]

在模板中:

{% for t1, t2 in test %}
<span class="inline">
<label>
<input type="radio" name="radio" checked/>
<span class="choice">{{t1.choice}}</span>
</label>
<label>
<input type="radio" name="radio" checked/>
<span class="choice">{{t2.choice}}</span>
</label>
</span>
{% endfor %}

更新:

您可以使用以下函数将test打包为2元组列表:


def pack(test):
new_test = list(zip(test[::2], test[1::2]))
if len(test) % 2:
new_test.append((test[-1], None))  # pay attention to None
return new_test

在容器中包装循环:

<div class="container">
{% for t in test%}
<label>
<input type="radio" name="radio" checked/>
<span class="choice">{{t.choice}}</span>
</label>
{% endfor %}
</div>

然后在css 中

.container {
display: flex;
flex-wrap: wrap;
}
.container label {
flex-basis: 50%;
}

https://codesandbox.io/s/lively-night-d2o1x

最新更新