WordPress.org

Codex

Attention Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

Javascript Reference/wp.template

Description

wp.template is used to create Underscore.js style template functions that, when executed, generates parametrized HTML for rendering. It is located in the wp scope/namespace.

Template Interpolation

WordPress defines its own interpolation tags using the _.template( options ) to avoid incompatibility in some PHP configurations with asp_tags enabled. The WordPress-specific interpolation syntax is inspired by Mustache templating syntax:

  • Interpolate (unescaped): {{{ }}}
  • Interpolate (escaped): {{ }}
  • Evaluate: <# #>

Template Definition

As with the default _.template() usage, you define your templates within a specially formed <script> tag, as such:

<script type="text/html" id="tmpl-my-template">
   <p>Hello {{{data.name}}}</p>
</script>

The script's type is text/html and it has an id that must start with tmpl-. Everything after the tmpl is the actual name you would like to use to reference your template later on.

To then access that template from JavaScript at runtime, you pass the name of the template to wp.template(), like this:

var template = wp.template('my-template');

This looks for the element with an ID of tmpl-my-template and returns a function to render that template and interpolate all the data fields.

Template Rendering

wp.template() returns a function, so don't try to attach the result of calling this to an HTML element, or even console.logging it out. Generally, you will assign the wp.template() result to a variable and then apply that variable (which is a function) with the data you would like to interpolate.

The example below assumes the use of jQuery to insert the result of the rendered template within an HTML element (stored in $el in this example).

var template = wp.template( 'my-template' );
$el.html( template( { name: "World" } ) );

$el now contains "Hello World". The value of the property "name" of the object that was passed as the argument of the template variable gets interpolated (because of the {{{ }}} in the template).

Interpolation Variable

To match the return structure of wp_send_json_success and wp_send_json_failure, wp_template binds the interpolation variable to the variable data. The implication of this is that you must prefix all your interpolation properties with data in order to avoid the dreaded Uncaught ReferenceError: <property> is not defined error.

<script type="text/html" id="tmpl-my-template">
   <p class="this works">Hello {{{data.name}}}</p>
   <p class="this fails">Goodbye {{{name}}}</p>
</script>

Location

This is defined in /wp-includes/js/wp-util.js

External Resources

Related