How to write JavaScript template in Magento2 : If want to append a clone of your html code on any event with different value then it will be the best practice to use JavaScript template , so here I am just going to explain the way to write this.
- Include JavaScript template to your phtml file –
123456789101112131415161718<button id="customer-button"><span>Click Here to get customer data</span></button><div id ="customer-container"><script id="customer-template" type="text/x-magento-template"><ul id="<%- data.id %>"><li>Name : <%- data.name %></li><li>Salary : <%- data.salary %></li><li>Location : <%- data.location %></li></ul></script></div> - Prepare Customer Data for setting in javascript template –
123456789101112$customerData = [['name' => "John Doe",'salary' => "1000 USD",'location' => "California"],['name' => "Jane Doe",'salary' => "800 USD",'location' => "Florida"],['name' => "Bob Doe",'salary' => "500 USD",'location' => "California"],];$jsonCustomerData = $this->helper('Magento\Framework\Json\Helper\Data')->jsonEncode($customerData); - Write javascript code for appending data in your js template
123456789101112131415161718192021require(["jquery",'mage/template',"mage/mage"], function ($, mageTemplate, alert){$('#customer-button').click(function(){$.each($.parseJSON('<?php echo $jsonCustomerData ?>'), function() {console.log('sss');var progressTmpl = mageTemplate('#customer-template'),tmpl;tmpl = progressTmpl({data: {name: this['name'],salary: this['salary'],location: this['location'],}});$('#customer-container').after(tmpl);});});}); - Now you will see a “button” and on click on this button customer data will be displayed as shown in the screenshot
So in this way you can write your own javascript template.
Be the first to comment.