简体   繁体   中英

Display selected elements twig template

data= [{id:1, text:'abc'},{id:2, text:'cde'}]

In my template I want to do this:

<ul>
  {{% for article in data %}}
  <li><a href={{article.id}}>{{article.id}}</a></li>
</ul>

In click on li I would display only the property "text" of related id.

<div>{{selected article.text}}</div>

If clicked 1 I want to see "abc".

Is there a way to do it with twig?

If I understand correctly, you cant to show dynamically the text related to an id on click on the li containing the related id.

This cannot be achieved with only twig. You need some javascript here. Basically what you can do is the following:

<ul>
  {% for article in data %}
    <li>
      <a href="#" data-content="{{ article.text|e('html_attr') }}" onclick="document.getElementById('dynamic-content').innerHTML = this.dataset.content; return false">
        {{ article.id }}
      </a>
    </li>
  {% endfor %}
</ul>
<div id="dynamic-content"></div>
  • |e('html') is some escaping for keeping it inside an html attribute, learn more here
  • onclick="" this contains pure javascript, it work like this but I recommand to do it another way (checkout this JSFiddle )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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