Mustache Templates in Totara

| By Webner

To write blocks of HTML directly in php/javascript by concatenating strings, a template is an alternative. Totara provides the templating language that is called Mustache. This is a new way to render the output. But, the output of using templates and directly using HTML will be the same.

The extension of the mustache template file is “.mustache”. There are some important things to learn about mustache templates:

  1. Calling a template from php:
    $OUTPUT->render_from_template('templatename', <tempaltecontext>);
  2. Calling a template from javascript:
    require(['core/templates', 'core/notification'], function(templates, notification) {
    var context = { name: testuser',email: ‘’ };
    templates.renderTemplate('block_userview/profile', context)
  3. To display a php variable value in html tag, use {{ }} brackets like:
    <span> {{username }} </span>
    To loop through all elements of the supplied array to your template, you have to write the code as below:
    <ul id="users">{{#userdata}}<li class="name">{{.}}</li>{{/userdata}}</ul>
  4. In these templates, there is no way to check the length of an array. In the above example, if “userdata” has no elements, then only <ul id=”users”></ul> tag will be created on the page which will be invalid html. So, to overcome this problem, you have to add a variable in the template context(passed to your template), which must contain a boolean value.
    For example:
    <ul id="users">
    {{#userdata}}<li class="name">{{.}}</li>{{/userdata}}
  5. When “userdata” will be empty, you can display “No user data available” using the inverse “operator ^ “:
    <p>No user data available</p>

This is an example of template:

We have to pass the JSON as below format to your template:
"text":"Example block",
"control_output":"<div id='action-menu-1'> ... </div>"
"content":"This is content part of your template,,
"footer_content":"This is the footer"

This is the html part of the template:
<div class="header block-header">
<div class="title block-title">
<div class="block_action"></div>
<h2 id="{{id}}" data-movetext="true">{{{text}}}</h2>
<div class="content block-content" data-movetext="true">
<div class="footer">

Leave a Reply

Your email address will not be published. Required fields are marked *