Using underscore 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', 'wp-util' ], 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 script’s type is text/html and it has an id that must start with tmpl- . The variables that you pass will be available data.propertyName

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

function my_data_template() { ?>

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

There are three tags you’ll want to know:

  • {{ var }} is used for HTML-escaped data.
  • {{{ var }}} is used for raw data (not escaped).
  • <# some_code() #> allows you to evaluate any JavaScript code.

Now all you have to do is use this in your main.js file like so :

// wp.template returns function which we can hold in postTemplate
const postTemplate = wp.template( 'my-template' );

const myData = {
   title   : 'This is awesome!',
   description  : 'This is description',
}

// We can pass the data inside postTemplate()
$( '.your-selector' ).html( postTemplate( myData ) );

This will insert your template with id tmpl-my-template inside the element with classname your-selector. Notice that when passing the id in wp.template(), we do not pass the prefix. So instead of tmpl-my-template we put my-template

0

Leave a Reply