Twig,添加第一类和最后一类
假设我有一个像这样的 for 循环:
{% for elem in arrMenu %}
<div class="topmenu-button">
<a href="{{ elem.url }}">{{ elem.name }}</a>
</div>
{% endfor %}
在这种形式下,它将呈现类似以下内容:
<div class="topmenu-button"><a href="url">name</a></div>
<div class="topmenu-button"><a href="url">name</a></div>
<div class="topmenu-button"><a href="url">name</a></div>
<div class="topmenu-button"><a href="url">name</a></div>
twig 如何帮助我添加 div 的第一个和最后一个类,以便我得到如下结果:
<div class="topmenu-button first"><a href="url">name</a></div>
<div class="topmenu-button"><a href="url">name</a></div>
<div class="topmenu-button"><a href="url">name</a></div>
<div class="topmenu-button last"><a href="url">name</a></div>
Let's say I have a for loop like this:
{% for elem in arrMenu %}
<div class="topmenu-button">
<a href="{{ elem.url }}">{{ elem.name }}</a>
</div>
{% endfor %}
In that form, it would render something like:
<div class="topmenu-button"><a href="url">name</a></div>
<div class="topmenu-button"><a href="url">name</a></div>
<div class="topmenu-button"><a href="url">name</a></div>
<div class="topmenu-button"><a href="url">name</a></div>
How can twig help me to add first and last classes the the div, so that I would have a result like:
<div class="topmenu-button first"><a href="url">name</a></div>
<div class="topmenu-button"><a href="url">name</a></div>
<div class="topmenu-button"><a href="url">name</a></div>
<div class="topmenu-button last"><a href="url">name</a></div>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以根据需要使用“特殊变量”
loop.first
和loop.last
。LINK
编辑:取决于您的数量关心“一个案例”,您可能需要这样的解决方案。
You can use the "special variables"
loop.first
andloop.last
for what you want.LINK
EDIT: depending how much you care about the "one case", you might need a solution like this.
由于循环不能同时是
first
和last
,我不想使用elseif
并编写 (DRY - if您将来必须更改topmenu-button
吗?):或更简洁:
编辑:这样您将在
class
中获得一些额外的空格属性(顺便说一句,这很好)。Edit2:这不会处理单元素数组(第一个=最后一个)
Since a loop can't be
first
andlast
at the same time, i would prefer not to useelseif
and write (DRY - what if you have to changetopmenu-button
in future?):or more concise:
Edit: this way you'll get some extra spaces in
class
attribute (it's perfectly fine btw).Edit2: this will not handle 1-element array (first = last)
如果是管理标签的类属性,三元条件会更好。
If it's to manage class attribut of a tag, a ternary condition would be better.
我在 Drupal 8 视图模板中使用它。感谢“elseif”,如果您只有 1 个项目,那么第一个项目永远不会获得“最后”类:
I use this in Drupal 8 views template. Thanks for 'elseif', if you have only 1 item, then the first item never get the 'last' class: