I’ve been using mustache for client-side HTML generation when working with AJAX but I recently discovered that WordPress ships a slightly modified version of Underscore.js template functionality. It is located under the
wp object and aptly named
In this post, I’ll walk through how you can use the
wp.template function to generate the HTML for your client-side code.
The code for the
wp.template is pretty simple. This is the whole code of it, which is located in the
As we can see, WordPress uses different settings for
_.template to prevent incompatibility with those PHP configurations that have
asp_tags enabled. If you’re used to doing templating in Mustache, you’ll feel just right at home.
However, there are two caveats that we’ll need to be aware of when using the
- We need to wrap our template with an id starting with
- All variables that we’re referencing in the template must be prefixed with
Let’s go through an example of implementing this. Assuming we have an array of objects that represents WordPress users like this:
We can then create a counterpart script for the template. The rules are simple:
- Escaped data can be printed using double curly braces, eg:
- Unescaped data is using triple curly braces, eg:
- Logic can be put inside
<# // our logic here #>
Using this set of rules, we can construct our template as follows:
To generate the HTML, first, call the
wp.template with the
id of our template.
Note: If you are getting an error of
Uncaught TypeError: wp.template is not a function, you might need to add
wp-util as a dependency for your enqueued script.
We don’t have to specify the full
id of the template (
tmpl-users) since the
wp.template will automatically prepend the
tmpl- part for us. The
wp.template will return a callable function, so to generate the HTML, we can then do the following:
The generated HTML should look like this:
We can then insert the generated
userHtml to the page using any of our preferred methods. That’s it!