1- Passing Information from Twig to JavaScript with Webpack Encore
2- ===============================================================
1+ Passing Information from Twig to JavaScript
2+ ===========================================
33
44In Symfony applications, you may find that you need to pass some dynamic data
55(e.g. user information) from Twig to your JavaScript code. One great way to pass
6- dynamic configuration is by storing information in ``data `` attributes and reading
6+ dynamic configuration is by storing information in ``data-* `` attributes and reading
77them later in JavaScript. For example:
88
99.. code-block :: html+twig
@@ -20,22 +20,24 @@ Fetch this in JavaScript:
2020.. code-block :: javascript
2121
2222 document .addEventListener (' DOMContentLoaded' , function () {
23- var userRating = document .querySelector (' .js-user-rating' );
24- var isAuthenticated = userRating .dataset .isAuthenticated ;
25- var user = JSON .parse (userRating .dataset .user );
26-
27- // or with jQuery
28- // var isAuthenticated = $('.js-user-rating').data('isAuthenticated');
23+ const userRating = document .querySelector (' .js-user-rating' );
24+ const isAuthenticated = userRating .getAttribute (' data-is-authenticated' );
25+ const user = JSON .parse (userRating .getAttribute (' data-user' ));
2926 });
3027
3128 .. note ::
3229
33- When `accessing data attributes from JavaScript `_, the attribute names are
34- converted from dash-style to camelCase. For example, ``data-is-authenticated ``
35- becomes ``isAuthenticated `` and ``data-number-of-reviews `` becomes
36- ``numberOfReviews ``.
30+ If you prefer to `access data attributes via JavaScript's dataset property `_,
31+ the attribute names are converted from dash-style to camelCase. For example,
32+ ``data-number-of-reviews `` becomes ``dataset.numberOfReviews ``:
33+
34+ .. code-block :: javascript
35+
36+ // ...
37+ const isAuthenticated = userRating .dataset .isAuthenticated ;
38+ const user = JSON .parse (userRating .dataset .user );
3739
38- There is no size limit for the value of the ``data- `` attributes, so you can
40+ There is no size limit for the value of the ``data-* `` attributes, so you can
3941store any content. In Twig, use the ``html_attr `` escaping strategy to avoid messing
4042with HTML attributes. For example, if your ``User `` object has some ``getProfileData() ``
4143method that returns an array, you could do the following:
@@ -46,4 +48,4 @@ method that returns an array, you could do the following:
4648 <!-- ... -->
4749 </div>
4850
49- .. _`accessing data attributes from JavaScript` : https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes
51+ .. _`access data attributes via JavaScript's dataset property ` : https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes
0 commit comments