1
- Passing Information from Twig to JavaScript with Webpack Encore
2
- ===============================================================
1
+ Passing Information from Twig to JavaScript
2
+ ===========================================
3
3
4
4
In Symfony applications, you may find that you need to pass some dynamic data
5
5
(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
7
7
them later in JavaScript. For example:
8
8
9
9
.. code-block :: html+twig
@@ -20,22 +20,24 @@ Fetch this in JavaScript:
20
20
.. code-block :: javascript
21
21
22
22
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' ));
29
26
});
30
27
31
28
.. note ::
32
29
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 );
37
39
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
39
41
store any content. In Twig, use the ``html_attr `` escaping strategy to avoid messing
40
42
with HTML attributes. For example, if your ``User `` object has some ``getProfileData() ``
41
43
method that returns an array, you could do the following:
@@ -46,4 +48,4 @@ method that returns an array, you could do the following:
46
48
<!-- ... -->
47
49
</div>
48
50
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