wp-util – Templating and more

Please use the WordPress utils whenever you do Templating in JavaScript. It is a very easy way to apply data to a template. Even writing the template is simple sandboxed HTML. Use it and enhance your website.

  • Simple infinite scroll using the REST API.
  • Append comments without reloading the page.
  • Show previews of the design while filling a form.

Templating

First create a template “foo”:

<script type="text/html" id="tmpl-foo">
 Yo {{ data.bar }} !

 Same but unescaped: {{{ data.bar }}}

 <# if ( data.baz ) { #>
  Make it so!
 <# } #>
</script>

As you can see the template is within a script part, so it will not be shown by the browser. There is a “tmpl-” prefix that wp-util needs to work:

var template = wp.template( 'foo' ); // this will fetch #tmpl-foo

// now fetch some data from AJAX or other source
var data = { bar: "Mama", baz: false };

// inject it and receive the generated HTML
var html = template( data );

// append it somewhere
$( '#somewhere' ).append( html );