What you'll learn with this guide
Where to use?
1) Data attributes
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 (_).
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.
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?
Try it without the mentioned methods and then with them. If it works, you will be able to log the object with the data.