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.
<div id ="employee"></div>
So the output of this snippet will be same as screenshot.

You can create and use any jquery template same as i did here.
If you have any query, please comment below.
Be the first to comment.