In this blog, I will show you how to use the JavaScript Templates in Magento 2. The following steps 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
Build your extensive multi-vendor marketplace platform with Magento 2 today!!!
How to use JavaScript templates in Magento 2?
<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 JSON. Afterward, utilize the mage/template to produce the HTML code. You can use the loop to create many students templates with 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. With this given information, you can manage the JavaScript Templates in Magento easily. Every store has a JavaScript Template in Magento 2 with different elements.
Leave a Reply