Securely render Javascript inside Magento 2 template files using PHP

Render Javascript inside phtml using php.png

Hello Magento Devs,

In today’s tutorial, we are going to learn the Standard way to securely render Javascript inside Magento 2 template files using PHP.

While working with Magento 2 template files (.phtml) we are required to use javascript of jQuery code inside the PHTML files.

No doubt, Magento 2 is so magical and there are lots of ways to add JavaScript to Magento 2.

For example,

Via <script type=”text/javascript></script>

In Magento Style (data-mage-init)

The imperative approach (Connecting JS modules like jQuery)

Via require-config.js file

Source : (Four Ways to Add JavaScript to Magento 2)

Today we are going to see a different approach to render javascript securely inside the .phtml template files using PHP.

Render Javascript securely in templates using PHP

You will get the idea by referring below example which is used in the native Magento 2 .phtml files.

Example :

As you can see Javascript code is injected using PHP with the use of

Note: Please take care that, while using this method you will have to remove $ at the time of using variables defined using var otherwise it will throw an error.