JavaScript, learn to use JavaScript, using JavaScript in WordPress, learn to code in WordPress, WordPress coding tips, WordPress coding tutorials, how to use wp.template, using wp.template, wp.template tutorial

How to Use wp.template, WordPress’ Underscore.js Template Method

Like many developer agencies, we have a few different audiences, including clients (current and prospective) and other developers. Our aim is to serve all of our audiences, who fall on a broad spectrum of technical knowledge. Even if you’re not a professional developer, we know that many of you still educate yourselves on the technology used on your site–and we want to help! If there’s anything we cover that you don’t understand (or anything you’d like to see us cover that’s WordPress related, even 101!), please let us know. There are no stupid questions.

That said, let’s dive into something fun: WordPress’ Underscore.js Template Method, wp.template.


If you’re not yet familiar, wp.template() is a cool little JavaScript utility method that is provided with the WordPress core ‘wp-util’ script. At its core, it uses the Underscorejs .template() method.

WordPress uses this utility to load templates for all of the backbone views, but backbone is not required to use it. First, I’ll demonstrate using wp.template() with a little jQuery in order to output some JavaScript data into an HTML template, then later as a bonus, we’ll rebuild wp.template() as our own module with some additional features.

Keep in mind: this is meant to be an example presented as simply as possible, and not something you would copy/paste into production code. Please continue to follow standard best practices, including things like putting JavaScript in its own file, avoiding anonymous functions, internationalizing your text strings, etc.

By default, the method requires a script tag with an id of tmpl-my-template-name. Because all of WordPress uses this templating method/system, you will want to make sure you properly prefix your ids, so as not to conflict with another template that may be loaded on the page. That script tag should also have a type of “text/template.”1

Let’s get started:

<?php 
function zao_item_status_tmpl() {
    ?>
    <script type="text/template" id="tmpl-zao-item-status">
        <span class="zao-status" data-id="{{ data.id }}">
        <# if ( data.status.name ) { #>
            <div class="zao-item-status">
                <span class="zao-status-color" style="display: inline-block;background-color:{{ data.status.color }};width:10px; height:10px;"></span>
                {{{ data.open }}}
                    {{ data.status.name }}
                {{{ data.close }}}
            </div>
        <# } else { #>
            &mdash;
        <# } #>
        </span>
    </script>
    <?php 
}

So now we have the proper script template tag ready to go in a PHP function, with unique id, tmpl-zao-item-status. As you can see, this isn’t 100% standard HTML. You can see we are using Mustache-inspired data variables, as well as Underscorejs logic blocks.

From the Codex:

WordPress defines its own interpolation tags using the _.template( options ) to avoid incompatibility in some PHP configurations with asp_tags enabled. The WordPress-specific interpolation syntax is inspired by Mustache templating syntax:

  • Interpolate (unescaped): {{{ }}}
  • Interpolate (escaped): {{ }}
  • Evaluate: <# #>

An important bit to understand is the <# and #>, which signals the opening/closing of raw JavaScript output, so you can do things like logic operators (like the if statement in the example above). You can also see we’re taking advantage of the unescaped interpolation when we output the data.open and data.close parameters, since those will contain HTML and we don’t want that escaped.

At this point, let’s hook into WordPress so we can see this in action.

Add this snippet somewhere in your theme’s functions.php file, or a custom plugin:

<?php 
// Output this at the top of the post-edit screen just below the title input.
add_action( 'edit_form_after_title', function() {
    ?>
    <span class="zao-status"><span style="display: inline-block;background-color:red;width:10px; height:10px;"></span> Please wait...</span>
    <?php 
} );

If you go to a new-post or post-edit screen, you should see something like this:

That doesn’t do much for us. We’re going to need some JavaScript setup to grab our updated status and update the status markup. To simplify, we’ll simply fake an AJAX request by setting a short delay. You could also using something like the Zao Mock API to mock some API requests/responses.

The JavaScript:

<?php 
function zao_item_status_js() {
    ?>
    <script type="text/javascript">
        // Wait for the dom to be ready..
        jQuery( function( $ ) {

            // Get the template function corresponding to our template markup.
            var template = wp.template( 'zao-item-status' ); // uses script tag ID minus "tmpl-"

            // Let's wait a tick, so we can see it go from yellow to green.
            setTimeout( function() {

                // Let's fake some data (maybe this is data from an API request?)
                var tmplData = {
                    id: 1,
                    status: {
                        name: 'Success!',
                        color: 'green'
                    },
                    open: '<span class="status-name" style="color:green">',
                    close: '</span>'
                };

                // Send the data to our new template function, get the HTML markup back.
                var html = template( tmplData );

                // Now let's replace the contents of the existing markup with our updated template markup.
                $( '.zao-status' ).html( html );
            }, 1000 );
        });
    </script>
    <?php 
}

The code comments should be self-explanatory, but to recap:

  1. Call wp.template() with the ID of the script tag we created earlier minus the tmpl- prefix
  2. Fake an API request by setting a one second delay
  3. Generate an object of data and pass it to our new template function which returns the compiled HTML
  4. Take that HTML and replace the existing.

We now have the JavaScript output in a PHP function, which we can hook into the footer. We have almost all the pieces we need to make this work, so let’s update our edit_form_after_title anonymous function:

<?php 
// Output this at the top of the post-edit screen just below the title input.
add_action( 'edit_form_after_title', function() {

    // Hook in our template script tag to the footer.
    add_action( 'admin_footer', 'zao_item_status_tmpl' );

    // Hook in our custom JS for updating the status.
    add_action( 'admin_footer', 'zao_item_status_js' );

    // Now, enqueue the WP util script so we can use wp.template
    wp_enqueue_script( 'wp-util' );

    // Make the initial output have a yellow status square
    ?>
    <span class="zao-status"><span style="display: inline-block;background-color:#ffe24d;width:10px; height:10px;"></span> Please wait...</span>
    <?php
} );

With that, we should see the status go from yellow (“Please wait…”) to green (“Success!”).

wp.template success! gif

wp.template success!

Hopefully, this basic example will help you get started using wp.template() in your own work, but if you have any questions, please leave comments below.

The full output for this example snippet can be found here.

If you’re still with me: now that we’ve covered the basics of the WordPress’ utility, you might be interested in a similar utility based on wp.template() which I created, _templatize. This script simplifies the above steps a little by combining the template-getting and data-sending, and also provides a feature that allows creating a template by passing it an HTML string (vs being tied to a tmpl- script tag in the dom). As a bonus, you can see the above snippet updated to use _templatize here.


  1. The key is that it shouldn’t be type="text/javascript" (or no type specified). More info 
Macbook laptop sitting on a brown table with WordPress dashboard open next to a cup of coffee, with the title "Yes, You Want Your Business Site on WordPress" across the lower center of the photo

Yes, You Want Your Business Site on WordPress

WordPress is powering more than a quarter of the web, but many businesses have shied away from taking the leap. Overhauling an entire site to move to a new content management system (CMS) can be intimidating. Businesses have a wide variety of concerns that prevent them from making such a big technology shift–even if the shift would be beneficial in the long-term. There are also a wide variety of myths surrounding what WordPress does and how it can benefit a business (or, rather, how it won’t).

I’m here to give you a few reasons that you want your business site on WordPress:

WordPress isn’t just for blogging

Although those of us in the WordPress industry already know this to be true, there are a lot of non-WordPress folk who still believe WP is just for blogging. Many of them aren’t even clear of what WordPress is.

WordPress provides all kinds of opportunities for your entire site, and it’s not just a place to host thoughts scribbled in a blog. Whether you want a member site, an e-commerce store, or a sleek, beautiful design to represent your company, WordPress can do all of that–and more. Since WordPress is endlessly advancing and changing, the bounds of what it can do are determined by the skill and creativity of the person building on it.

The learning curve is a little steep, but it’s worth it

Although WordPress boasts a five minute install, the average person is going to spend a bit longer setting it up. For someone who doesn’t have the technical savvy, getting a WordPress site set up the way that they want can be a challenge.

Don’t let that stop you from taking it on!

One of the best parts about WordPress is that it’s open source software, which means the source code is available to the public for study, alteration, and distribution. Most of the folks in WordPress are deeply committed to advancing open source software and giving back to the public by making it better and faster. The best and brightest professionals are giving their time to make a free software the absolute best it can be–which benefits all of us.

The work developers do requires expertise and skill, and when you hire them to do the work for your business, you pay for their extensive time and effort. In addition to that, they provide a public service by making WordPress, a free tool, widely beneficial and accessible to everyone. You may hire one developer, but when you work with WordPress, you benefit from the community work of countless brilliant minds.

If you stop and think a moment about all the people who generously give their time and knowledge, often without compensation, to create one of the strongest platforms available, you’ll realize it’s a community worth joining.

Since WordPress enthusiasts, professionals and amateurs alike, are so dedicated to enhancing the software and innovating with the tools provided, there are a ton of resources available for learning how to do what you want to your site. Sites like WPBeginner and WP101 aim to educate people on the fundamentals of WordPress, and if you do some Googling, you’ll easily find a wealth of answers to almost any question you have.

If you’re still worried about that learning curve, many WordPress developers and designers offer WordPress education as a part of their services, so the day to day dealings can be handled by you or your staff without a struggle.

WordPress makes content management easy

Yes, WordPress is a content management system, but that doesn’t just refer to blogging. “Content” describes nearly everything on your site–videos, photos, and text.

As a CMS, WordPress is the absolute best. Once you learn the basic terminology and know where things are in the dashboard, updating your site is easy peasy.

Even if you have a staff of Luddites, teaching them how to handle basic content management in WordPress is super simple! This means your staff will be empowered to make those changes and can handle the content on your site as a part of their duties. This means less oversight from you, which gives you time to focus on running your business. Empowering your staff to use your technology allows you to delegate responsibly and allocate your time to where you need it most.

Integrating with WordPress opens up your audience

One of the ways we’ve helped our clients is by building them their own WordPress plugin. This is particularly helpful for companies that offer a digital product or service and have a target audience that is building out their own business sites.

We have an example of this from our own experience:

Quantcast Corporation is a technology company that provides real-time measurement and analysis of advertising and audience engagement. Quantcast hired us to create a WordPress plugin that puts a JavaScript snippet in the header of their users’ sites. This extended their service out to the greater WordPress community and provided a huge benefit to their existing users. Quantcast users with WordPress websites can install the Audience Analytics plugin. Then, their Quantcast account is linked directly to their WordPress site and they can access their site analytics through WordPress super easily.

WordPress can scale–which means it can grow with your business

To make it do so successfully, though, you’ll definitely need the assistance of a professional. This part gets a little technically advanced, but Smashing Magazine took a look at what different developers have done to set up high traffic sites for success. WordPress isn’t the only key component in the fight to keep your site performant, but it’s not going to be what holds you back.

Getting on WordPress means being in good company

There are tons of businesses and major publications that are on WordPress, including:

  • WorldPay
  • Amazon
  • Disney
  • Politico
  • The NBA
  • Discovery Communications
  • USA Today
  • Microsoft Office Blogs
  • FiveThirtyEight
  • Airbnb

And many, many more. Big names take their technology seriously, and they’ve chosen WordPress to best serve their massive audiences.

So what are you waiting for?