Back to Top

Create JQuery Templates in Magento2

Updated 21 November 2016

We can use jQuery templates in Magento2 and you don’t need to include any third party library for that.

JQuery Templates in Magento2

First of all you need to define a template. And then you can use it by ‘mage/template‘ in js file.

Here i am creating template for some employee information.

<script id="employee-template" type="text/x-magento-template">
   <ul>
        <li>
           Employee Id : <%- data.id %>
        </li>
        <li>
           Employee Name : <%- data.name %>
        </li>
        <li>
           Employee Salary : <%- data.salary %>
       </li>
   </ul>
</script>

Now include javascript code.

<script>
require([
    "jquery",
    "mage/template"
    ], function ($, template) {
        var employeeData = [
                            {"id":"101","name":"John","salary":"50000"},
                            {"id":"102","name":"Paul","salary":"30000"},
                            {"id":"103","name":"Peter","salary":"45000"}
                        ];
        $.each(employeeData, function() {
            var employeeTemplate = template('#employee-template');
            var employee = employeeTemplate({
                                data: {
                                    name: this['name'],
                                    id: this['id'],
                                    salary: this['salary']
                                }
                            });
            $('#employee').append(employee);
        });
    });
</script>

Finally define a html element where you want add and display this data.

Searching for an experienced
Magento 2 Company ?
Find out More
<div id ="employee"></div>

So the output of this snippet will be same as screenshot.
JQuery Templates

You can create and use any jquery template same as i did here.

If you have any query, please comment below.

. . .

Leave a Comment

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


Be the first to comment.

Back to Top

Message Sent!

If you have more details or questions, you can reply to the received confirmation email.

Back to Home