Skip to content

Commit 2466fc1

Browse files
committed
minor #9528 Replace jQuery example with plain JavaScript (msheakoski)
This PR was submitted for the master branch but it was squashed and merged into the 3.4 branch instead (closes #9528). Discussion ---------- Replace jQuery example with plain JavaScript The data attributes example relies unnecessarily on jQuery and is potentially more confusing because it masks how attributes actually work in JavaScript and it's another level of abstraction to deal with. It is a better idea to promote web standards here because people tend to copy what they see, so let's steer them in a future-friendly direction. Commits ------- 0dfcbd8 Replace jQuery example with plain JavaScript
2 parents 1e9e842 + 0dfcbd8 commit 2466fc1

File tree

1 file changed

+12
-5
lines changed

1 file changed

+12
-5
lines changed

frontend/encore/server-data.rst

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,18 @@ Fetch this in JavaScript:
1616

1717
.. code-block:: javascript
1818
19-
// jquery isn't required, but makes things simple
20-
var $ = require('jquery');
21-
22-
$(document).ready(function() {
23-
var isAuthenticated = $('.js-user-rating').data('is-authenticated');
19+
document.addEventListener('DOMContentLoaded', function() {
20+
var userRating = document.querySelector('.js-user-rating');
21+
var isAuthenticated = userRating.dataset.isAuthenticated;
2422
});
2523
24+
.. note::
25+
26+
When `accessing data attributes from JavaScript`_, the attribute names are
27+
converted from dash-style to camelCase. For example, ``data-is-authenticated``
28+
becomes ``isAuthenticated`` and ``data-number-of-reviews`` becomes
29+
``numberOfReviews``.
30+
2631
There is no size limit for the value of the ``data-`` attributes, so you can
2732
store any content. In Twig, use the ``html_attr`` escaping strategy to avoid messing
2833
with HTML attributes. For example, if your ``User`` object has some ``getProfileData()``
@@ -33,3 +38,5 @@ method that returns an array, you could do the following:
3338
<div data-user-profile="{{ app.user ? app.user.profileData|json_encode|e('html_attr') : '' }}">
3439
<!-- ... -->
3540
</div>
41+
42+
.. _`accessing data attributes from JavaScript`: https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes

0 commit comments

Comments
 (0)