0
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?

Andy88
  • 647
  • 2
  • 9
  • 21
  • No, you can't do this with twig - [reference](https://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming) – DarkBee Mar 09 '20 at 15:29

1 Answers1

0

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)
Nek
  • 2,715
  • 1
  • 20
  • 34