Blog

How to Use UnderscoreJS as a Templating Engine

UnderscoreJS-Magento

Table of Contents

Underscore JS is a compact, yet wonderful JS library that “provides a whole mess of useful functional programming helpers without extending any built-in objects“. The best part is, Underscore JS comes out-of-the-box, with Magento 2.x. In this tutorial, we’re going to see how we can use Underscore JS as a templating engine, within Magento 2.

It is advisable to understand what jQuery widgets are and how to instantiate widgets the Magento way first before continuing with this tutorial.

Task

Display products in a template being fetched dynamically, using AJAX.

Solution

Define our block file

app/code/Codilar/HelloWorld/Block/Underscore.php
<?php
/**
 *
 * @package     magento2
 * @author      Codilar Technologies
 * @license     https://opensource.org/licenses/OSL-3.0 Open Software License v. 3.0 (OSL-3.0)
 * @link        https://www.codilar.com/
 */

namespace Codilar\HelloWorld\Block;

class Underscore extends Template
{
    /**
     * @return string
     */
    public function getUnderscoreTemplate() {
        return "Codilar_HelloWorld/template/underscore.html";
    }
}

In our template file, define our widget

app/code/Codilar/HelloWorld/view/frontend/templates/underscore.phtml
<?php
/* @var \Codilar\BoughtBefore\Block\Underscore $block */
?>
<div class="template_container"></div>

<script type="text/x-magento-init">
    {
        ".template_container" : {
            "myProductWidget" : {
                "template" : "<?= $block->getUnderscoreTemplate() ?>"
            }
        }
    }
</script>

Next, we define our JS file in the requirejs-config

app/code/Codilar/HelloWorld/view/frontend/requirejs-config.js
var config = {
    map: {
        '*': {
            'myProductWidget':  'Codilar_HelloWorld/js/widget'
        }
    }
};

And finally, we define our JS file containing the widget

app/code/Codilar/HelloWorld/view/frontend/web/js/widget.js
require([
    'jquery',
    'underscore',
    'mage/url'
], function ($, _, urlBuilder) {
    var widget = {
        /* default values. Can be overridden when initializing the widget */
        options: {
            template: ""
        },
        _create: function () {
            this._initTemplate();
        },
        _initTemplate: function () {
            require("text!"+this.options.template, function (template) {
                this.showProducts(_.template(template));
            }.bind(this));
        },
        showProducts: function (template) {
            var self = this;
            $.ajax({
                url: urlBuilder.build("underscore/products/get"),
                method: "GET",
                success: function (products) {
                    self.element.html(template(products));
                }
            });}
    };

    return $.widget('codilar.myProductWidget', widget);
});

And then in our app/code/codilar/HelloWorld/view/frontend/web/template/underscore.html file, we write the actual underscore template

<% if (products.length > 0 ) { %>
    <% products.forEach (function (product) { %>
        <a href="<%= product.url %>"><%= product.name %></a>
    <% }); %>
<% } %>

For documentation on how to build Underscore templates, check this link out

NOTE: The app/code/Codilar/HelloWorld/Controller/Products/Get.php controller must be created on your own for this tutorial to work. Do have a look at the Hello World module to understand how to make routes and Controllers.

Well that’s all. Thank’s a lot for sticking through. Do let us know in the comment section below about what you want our next Magento tutorial blog to be about.

***

Previous Tutorials

What is x-magento-init?

What is KnockoutJS and how is it relevant in Magento 2?

Picture of Arijit Panigrahi

Arijit Panigrahi

I am experienced in Magento development specialising in PHP, HTML, jQuery, and PWA projects with expertise in GraphQL, algorithm design, and database design, I have delivered high-quality solutions for diverse clients. I am experienced in algorithm design, optimizing application performance, and database efficiency. With a commitment to professionalism and a passion for continuous learning, remain at the forefront of web development innovation.

You May Also Like

Latest Blogs

Magento Development Company

Let’s talk

Our Offices

DTECH, Techno Hub 1, Dubai Silicon Oasis Authority, United Arab Emirates – Dubai – United Arab Emirates

Singapore

Codilar Digital Pte Ltd, 68 Circular Road, #02-01, 049422, Singapore

India

Bengaluru

7th Floor, Jupiter Block ,Prestige Tech Park, Kadubeesanahalli, Bellandur Amanikere, Bengaluru, Karnataka 560103

Calicut

SBC No 4 & 6 upper basement, Sahya Building
KSITIL SEZ, Cyberpark Kozhikode Park Rd, Nellikkode, Kozhikode, Kerala 673016

Kolkata

Astra Towers, ANO -523 ,North Block, Action Area IIC, Newtown, Kolkata, West Bengal 700135

Ahmedabad

Codilar Technologies, Connekt, 13th Floor, Gala Empire, Opposite T.V. Tower, Drive In Rd, Memnagar, Ahmedabad, Gujarat – 380052

Oman

Building No. 2/796, Way No. 43, Block No. 336, Al Khud 132, Muscat, Oman

Codilar

© Copyright Codilar 2025. All Rights Reserved. Privacy Policy

Send Feedback

Request PWA Demo