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' } ));

You can write both javaScript and php here in this template. For example:

		<script type="text/html" id="tmpl-integrations-template">
			<div class="columns large-4 medium-6 small-12 ci-int-results__wrap">

				<a href="<%= postPermalink %>" class="ci-int-result">
					<div class="ci-int-result__content">
						<% if ( postTitle ) { %>
<?php echo 'Hi' ?>
							<h3 class="ci-int-result__title"><%= postTitle %></h3>
						<% } %>
						<% if ( postExcerpt ) { %>
							<p class="ci-int-result__desc"><%= postExcerpt %></p>
						<% } %>
					</div>

					<% if ( journeyName ) { %>
						<div class="ci-int-result__journey"><span class="ci-int-result__journey-content"><%= journeyName %></span></div>
					<% } %>

					<% if ( brands.length ) { %>
						<div class="ci-int-result__brand">
						<% for ( let i = 0; i < brands.length; i++ ) { %>
							<span class="ci-int-result__brand-list"><img src="<%= brands[ i ].img_url %>" class="attachment-full ci-int-result__brand-img" alt="<%= brands[ i ].name %>"></span>
						<% } %>
						</div>
					<% } %>
				</a>
			</div>
		</script>

Leave a Reply