As a team of WordPress developers, we often stumble upon a task where we need to request a set of data using AJAX and render it to the browser.
Most of the the time we do it like this:
It works. However, it’s difficult to maintain this code, and most of the time, the HTML markup we need to use is much more complex than the example above. As more updates and changes occur in the markup, we find it increasingly difficult to work with this code.
Enter wp.template
If you are familiar with Underscore.js or {{ mustache }}, wp.template
is an underscore-based JavaScript templating helper shipped with WordPress.
So, how do we use it?
Create and render your HTML markup template
Just with this, we can immediately see how easy it is to maintain our HTML markup.
Notes
1. It is important that the HTML markup template is wrapped with <script type=“text/html” id=“tmpl-[TEMPLATE-NAME]”></script>
.
2. The id
needs to be prefixed with tmpl-
.
3. data
is the variable passed to the template from the JavaScript. You’ll see this shortly.
4. JavaScript logic goes inside <# #>
.
5. <# _.forEach() #>
is an Underscore function. See Underscore.js.
6. Use {{ }}
for escaping output.
7. Use {{{ }}}
for unescaped output. Using {{ }}
with data containing markup will convert the tags to HTML entities. So for example, if the data is <img src=""/>
and we indeed want to render the image, we need to use {{{ }}}
.
Load wp-util
The code for wp.template
is inside wp-util, so we need to make sure that wp-util.js
is loaded.
You can do this by adding wp-util
as a dependency of your JavaScript. Like this:
wp_enqueue_script( 'custom_js', plugins_url( 'js/custom.js', __FILE__ ), [ 'jquery', 'wp-util' ] );
The JavaScript
A few more notes…
1. We omit tmpl-
in wp.template( 'display-posts' )
.
2. The data we pass to display_posts_template()
is the data
variable we use in our template.
Conclusion
While we used <# _.forEach() #>
in our example, it is a good idea to minimize the JavaScript logic in your template. The goal is to separate the “view” and “logic.”
For example, you can approach our example like this:
JavaScript
Template
wp.template
is a good tool to create clean and maintainable code. Another advantage of using this technique is you don’t need to modify your JavaScript when you modify your HTML template. As a developer, it means no re-compiling / bundling / minifying / purging of JavaScript cache is needed.
What do you think? Will these tips help you with a better, cleaner way to render HTML with JavaScript? Leave us a comment below. Need a team to offer up solutions like this for your website project? Contact us today.
Hey Michael, you have given a wonderful tip to render HTML with javascript. It is very important to render HTML and javascript to get load your website faster in the browser. Thanks for the tips.