Skip to content

Replace jQuery example with plain JavaScript #9528

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 3, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 12 additions & 5 deletions frontend/encore/server-data.rst
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,18 @@ Fetch this in JavaScript:

.. code-block:: javascript

// jquery isn't required, but makes things simple
var $ = require('jquery');

$(document).ready(function() {
var isAuthenticated = $('.js-user-rating').data('is-authenticated');
document.addEventListener('DOMContentLoaded', function() {
var userRating = document.querySelector('.js-user-rating');
var isAuthenticated = userRating.dataset.isAuthenticated;
});

.. note::

When `accessing data attributes from JavaScript`_, the attribute names are
converted from dash-style to camelCase. For example, ``data-is-authenticated``
becomes ``isAuthenticated`` and ``data-number-of-reviews`` becomes
``numberOfReviews``.

There is no size limit for the value of the ``data-`` attributes, so you can
store any content. In Twig, use the ``html_attr`` escaping strategy to avoid messing
with HTML attributes. For example, if your ``User`` object has some ``getProfileData()``
Expand All @@ -33,3 +38,5 @@ method that returns an array, you could do the following:
<div data-user-profile="{{ app.user ? app.user.profileData|json_encode|e('html_attr') : '' }}">
<!-- ... -->
</div>

.. _`accessing data attributes from JavaScript`: https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes