Read More
Read More
Menu Close

    How to write JavaScript template in Magento2

    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.

    1. Include  JavaScript template to your phtml file –
      <button id="customer-button">
          <span>Click Here to get customer data</span>
      <div id ="customer-container">
          <script id="customer-template" type="text/x-magento-template">
              <ul id="<%- %>">
                      Name : <%- %>
                      Salary : <%- data.salary %>
                      Location : <%- data.location %>
    2. Prepare Customer Data for setting in javascript template –
      $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);
    3. Write javascript code for appending data in your js template
      ], function ($, mageTemplate, alert){
          	$.each($.parseJSON('<?php echo $jsonCustomerData ?>'), function() {
                  var progressTmpl = mageTemplate('#customer-template'),
                  tmpl = progressTmpl({
                      data: {
                          name: this['name'],
                          salary: this['salary'],
                          location: this['location'],
    4. 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.

    Searching for an experienced
    Magento 2 Company ?
    Read More
    . . .
    Discuss on Helpdesk

    Leave a Comment

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

    Be the first to comment.

    Back to Top