How to use JavaScript templates in Magento 2

In this Blog, I will show you how to use the JavaScript Template in Magento 2. The following steps which help you to use the JavaScript template in Magento 2.

Step 1: In the .phtml file, please write the script

Step 2:Process the data to fill the mage/template

Now in the .phtml file, please write the script

<span style="font-weight: 400;">  </span>

<script id="student-template" type="text/x-magento-template">

       <ul id="<%- data.id %>">

           <li>

               Student Name : <%- data.name %>

           </li>

           <li>

               Class : <%- data.class %>

           </li>

       </ul>

   </script>

Practice the data to fill the mage/template

The data must be the JSON. Afterward, utilize the mage/template to produce the HTML code. You can use the loop to create many students template by JavaScript.

<?php

$studentData = [

   [

       'name' => "User 1",

       'class' => "A"

   ],

   [

       'name' => "User 2",

       'class' => "B"

   ]

];

$jsonData = $this->helper('Magento\Framework\Json\Helper\Data')->jsonEncode($studentData);

?>

<div id ="student"></div>

<script>

   require([

       "jquery",

       'mage/template',

       "mage/mage"

   ], function ($, mageTemplate){

       $.each($.parseJSON('<?php echo $jsonData ?>'), function() {

           var progressTmpl = mageTemplate('#student-template'),

               tmpl;

           tmpl = progressTmpl({

               data: {

                   name: this['name'],

                   salary: this['class']

               }

           });

           $('#student').after(tmpl);

       });

   });

</script>

<div id ="student"></div>

The steps I mentioned above are the simple and shortest process for you to do JavaScript Template in Magento 2. With this given information, you can manage the JavaScript Template in Magento 2 easily. Every store has a JavaScript Template in Magento 2 with different elements.

Last Update: February 22, 2019  

February 16, 2018   464   Nandini R    Java Script    
Total 2 Votes:
0

Tell us how can we improve this post?

+ = Verify Human or Spambot ?

Leave a Reply

Your email address will not be published. Required fields are marked *

Facebook
Twitter
INSTAGRAM
LinkedIn