How to format and send data from Twig to JavaScript
What you'll learn with this guide
In this guide, you will learn about passing arrays, objects, and values from Twig to JavaScript with the help of data attributes, window objects, and methods which are JSON encode, parse and escape.
Where to use?
These methods are used for passing any arrays and objects from the backend through Twig to JavaScript. In this process, we transform complex data so it would be easier to use it. We transform data to objects and with that, enable accessing individual values using the dot notation.
Solution
1) Data attributes
Data attributes allow us to store data inside HTML tags and access them through JavaScript and CSS.
To use data attributes, firstly we need to add the attribute starting with ‘data-’ to an element. The names of data attributes must contain only letters, but without capital letters, numbers, hyphen (-), dot (.), colon (:) or underscore (_).
In Vanilla JavaScript we fetch the data using the .getAttribute() method:
Fetching the data in jQuery is simple - we need to use the .data() method:
2) |json_encode() twig filter and fetching data
This method is used to convert arrays and objects to JSON value and to pass arrays and objects through data attributes.
Twig:
JQuery:
Output:
3) |json_encode(), |escape() and JSON.parse()
If we instead want to use a window object to pass data first we need to use json_encode to convert the object to JSON value.
Output without |escape() and JSON.parse:
When we console log the data, we get unwanted characters that we remove using the escape method. In this example we use |escape(‘js’) to get a cleaner output:
Output with |escape() but without JSON.parse:
After this, we use the JSON.parse() which is used to convert text into an object:
Final output with \escape and JSON.parse():
All of the methods mentioned are also used with arrays:
Output without |escape() and JSON.parse():
Output without JSON.parse() but with escaping special characters:
Final output after converting from text to object:
Does it work?
To test this, you can use a sample array or object and try to pass it through the data attribute and then get it in JavaScript or jQuery.
Try it without the mentioned methods and then with them. If it works, you will be able to log the object with the data.