Using Underscore JS _.template() in WordPress

Many times we come across a situation in JavaScript where we have to generate dynamic html

let content = '<li class="list-item">' +
	'<div class="details">' +
			'<h3>{ title }</h3>' +
			'<p>{ description }</p>' ++
	'</div>' +
'</li>';

You can see the code above looks messy and difficult to read. 
WordPress recommends to use underscore templates.
WordPress already has support for underscore.js library. All you have you to do is enqueue it like so :

wp_register_script( 'my-script', 'path/to/your/main.js', [ 'jquery', 'underscore' ], false, true );

Then you can create a template in a php file e.g. my-template.php and hook it to the wp_footer hook using add_action . This will add your script at the bottom of your page . The variables that you pass will be available in propertyName

<%= … %> is used to pass variables.
<% … %> is used to insert JS code.
<%- … %> is used for HTML escaped value

<?php
add_action( 'wp_footer', 'my_data_template' );

function my_data_template() { ?>

	<script type="text/html" id="my-template">
		<li class="list-item <%= className %>">
			<div class="details">
				<h3><%= title %></h3>
				<p><%= description %></p>
			</div>
		</li>
	</script>
<?php }

Make sure you include this file ( e.g. in functions.php )

Now all you have to do is get the html content of the above script. Call the _.template() by passing this template inside of it. _.template() will return a function which you can then use to pass the data inside of it and append it where you want like so :

	var template = jQuery("#my-template").html();
	var templateFunc = _.template( template );


	jQuery("body").html( templateFunc( {title: 'Imran', description: 'my desc', className: 'some-class' } ));
1+

Leave a Reply