Skip to content

Commit 417651e

Browse files
committed
minor #19473 [Frontend] Some smaller updates (ThomasLandauer)
This PR was merged into the 6.4 branch. Discussion ---------- [Frontend] Some smaller updates * **Please move this page out of the `/encore/` hierarchy!** This is general info that also applies to *any* JavaScript. That's why I already changed the title. * I removed jQuery cause I think it shouldn't be advertised anymore today. Commits ------- b97c890 [Frontend] Some smaller updates
2 parents c09b005 + b97c890 commit 417651e

File tree

1 file changed

+9
-13
lines changed

1 file changed

+9
-13
lines changed

frontend/encore/server-data.rst

Lines changed: 9 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
1-
Passing Information from Twig to JavaScript with Webpack Encore
2-
===============================================================
1+
Passing Information from Twig to JavaScript
2+
===========================================
33

44
In 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
77
them later in JavaScript. For example:
88

99
.. code-block:: html+twig
@@ -20,22 +20,18 @@ 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.dataset.isAuthenticated;
25+
const user = JSON.parse(userRating.dataset.user);
2926
});
3027
3128
.. note::
3229

3330
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``.
31+
converted from dash-style to camelCase. For example, ``data-number-of-reviews`` becomes
32+
``dataset.numberOfReviews``.
3733

38-
There is no size limit for the value of the ``data-`` attributes, so you can
34+
There is no size limit for the value of the ``data-*`` attributes, so you can
3935
store any content. In Twig, use the ``html_attr`` escaping strategy to avoid messing
4036
with HTML attributes. For example, if your ``User`` object has some ``getProfileData()``
4137
method that returns an array, you could do the following:

0 commit comments

Comments
 (0)