How to pass parameters from *.phtml to a JavaScript component using x-magento-init

(Dmitry Fedyuk) #1

x-magento-init is the proper way to run some JavaScript code from a *.phtml template.
The official documentation refers such JavaScript code as a JavaScript component.
You can pass some parameters from PHP to JavaScript with x-magento-init.
An example from the core:

The code pass 3 parameters to the JavaScript component: attributesData, isSortable, isReadOnly.
How can the parameters be accessed by the component? Let’s look at its code:

As you can see, the component is an AMD module.
The module returns a function and the parameters are passed to the function like an object (named config in this case).

Then the component can use it, for example:


How to insert some JavaScript to a *.phtml template in the proper way (x-magento-init)
How to load JavaScript or stylesheet conditionally depends on backend config settings?
How to add JavaScript / CSS / Less with a custom module
How to program the media browser
How to add a stylesheet to a page after the layout has already been built?
(Dmitry Fedyuk) #2

Please note that your JavaScript component should be an AMD module so you shoud use top-level define function, not require.


(Dmitry Fedyuk) #3

See also: