From 0dfcbd8b182d6aee8b8b1688c6bcdad6aeec11b2 Mon Sep 17 00:00:00 2001 From: Michael Sheakoski Date: Sat, 31 Mar 2018 02:30:23 -0400 Subject: [PATCH] Replace jQuery example with plain JavaScript --- frontend/encore/server-data.rst | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/frontend/encore/server-data.rst b/frontend/encore/server-data.rst index 07d9a522383..8e780751e54 100644 --- a/frontend/encore/server-data.rst +++ b/frontend/encore/server-data.rst @@ -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()`` @@ -33,3 +38,5 @@ method that returns an array, you could do the following:
+ +.. _`accessing data attributes from JavaScript`: https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes