Mustache Templates in Totara

Webner Solutions
2 min readFeb 4, 2022

--

Mustache Templates in Totara
Mustache Templates in Totara

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:

Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.

Originally published at https://blog.webnersolutions.com on February 4, 2022.

--

--

Webner Solutions
Webner Solutions

Written by Webner Solutions

Our team in Salesforce is very strong, with in-depth knowledge of Salesforce classic and Lightning development as well as the Service cloud.

No responses yet