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>
      </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>
    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
      require([
          "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);
              });
          });
      });
    4. Now you will see a “button” and on click on this button customer data will be displayed as shown in the screenshot
      FlQRBKD

    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