简体   繁体   English

在Twig中动态设置html id属性

[英]Set html id attribute dynamically in Twig

I'm trying to set the id of an element using a variable in a Twig template (not a form) without using JavaScript. 我试图在不使用JavaScript的情况下使用Twig模板(而不是表单)中的变量设置元素的id。 The template code looks like this: 模板代码如下所示:

{% set show_id = 'show' ~ entity.id %}
{{ dump(show_id) }}
<div class="event_option" id="show_id">
    <a href="{{ path('event_show', { 'id': entity.id }) }}">show</a>
</div>

The show_id variable is dump 'ed correctly, but when I try to use it as the html id in id="show_id" , the id that gets assigned to the div is the string "show_id", and not the actual value of show_id . show_id变量正确dump ,但是当我尝试将其用作id="show_id"的html id时,分配给div的id是字符串“show_id”,而不是show_id的实际值。 I get the same result when no parenthesis are used when assigning the html id, as in id=show_id . 如果在分配html id时没有使用括号,我会得到相同的结果,如id=show_id How can I access the Twig variable when assigning the html id attribute? 如何在分配html id属性时访问Twig变量?

You should enclose with double bracket to tell Twig to print the value of variable 你应该用双括号括起来告诉Twig打印变量的值

<div class="event_option" id="{{show_id}}">
    <a href="{{ path('event_show', { 'id': entity.id }) }}">show</a>
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM