Stevan Tosic Stevan Tosic - 1 year ago 120
Twig Question

Send associative array from HTML to JS

I need to send few values through html data attribute to JS.

<div class="article"
data-article="[{% for data in article %}{{ data }},{% endfor %}]"

I use foreach to get each element of existing associative array to create new one which is in data attribute.

This works well but I want to send whole array in this case article if there is some way for that

I know that array can be send via data HTML attribute but I wonder if I can send associative array in reason to avoid multi data attributes in one html element.

Answer Source

I would use JSON in this case

when you build the html with php use


Now the html will have the array. you can decode it in JS with