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: ‘testuser@gmail.com’ };
    templates.renderTemplate('block_userview/profile', context)
    .done(doneCallback)
    .fail(notification.exception);
    });
  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:
    {{#userdata_has_items}}
    <ul id="users">
    {{#userdata}}<li class="name">{{.}}</li>{{/userdata}}
    </ul>
    {{/userdata_has_items}}
  5. When “userdata” will be empty, you can display “No user data available” using the inverse “operator ^ “:
    {{^userdata_has_items}}
    <p>No user data available</p>
    {{/userdata_has_items}}

This is an example of template:

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

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

Leave a Reply

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