Templates

Revision as of 10:19, 10 May 2017 by Ryan Wyllie (talk | contribs) (What other helpers can I use?)

Jump to: navigation, search

Moodle 2.9


Contents

Templates

What is a template?

A template is an alternative to writing blocks of HTML directly in javascript / php by concatenating strings. The end result is the same, but templates have a number of advantages:

  • It is easier to see the final result of the template because the code for a template is very close to what the final HTML will look like
  • Because the templating language is intentionally limited, it is hard to introduce complex logic into a template. This makes it far easier for a theme designer to override a template, without breaking the logic
  • Templates can be rendered from javascript. This allows ajax operations to re-render a portion of the page.

How do I write a template?

Templates are written in a language called "Mustache". Mustache is written as HTML with additional tags used to format the display of the data. Mustache tags are made of 2 opening and closing curly braces
{{tag}}
. There are a few variations of these tags that behave differently.
  • {{raiden}}
    This is a simple variable substitution. The variable named "raiden" will be searched for in the current context (and any parent contexts) and when a value is found, the entire tag will be replaced by the variable (HTML escaped).
  • {{{galaga}}}
    This is an unescaped variable substitution. Instead of escaping the variable before replacing it in the template, the variable is included raw. This is useful when the variable contains a block of HTML (for example).
  • {{#lemmings}} jump off cliff {{/lemmings}}
    These are opening and closing section tags. If the lemmings variable exists and evaluates to "not false" value, the variable is pushed on the stack, the contents of the section are parsed and included in the result. If the variable does not exist, or evaluates to false - the section will be skipped. If the variable lemmings evaluates to an array, the section will be repeated for each item in the array with the items of the array on the context. This is how to output a list.
  • {{^lemmings}} enjoy view {{/lemmings}}
    Equivalent of "if-not" block, there is no "else" in mustache.
  • {{> franken_style/name_of_template }}
    This is a partial. Think of it like an include. Templates can include other templates using this tag. In the called template, the data it sees (for including values is the same as the data available where the partial is included.
  • {{$blockvar}} ... {{/blockvar}}
    This is a block variable. It defines a section of the template that can be overridden when it's included in another template.
  • {{< template_name}} ... {{/template_name}}
    This is similar to including a partial but specifically indicates that you'd like to override one or more block variables defined within the template you're including. You can override the block variables by defining a block variable within these tags that matches the name of the block variable you'd like to override in the included template.

So - putting this all together:

recipe.mustache

<h3>{{recipename}}</h3>
<p>{{description}}</p>
<h4>Ingredients</h4>
<ol>
{{#ingredients}}
<li>{{.}}</li>
{{/ingredients}}
</ol>
<h4>Steps</h4>
<ol>
{{#steps}}
<li>{{{.}}}</li>
{{/steps}}
</ol>
{{ > ratethisrecipe }}

When given this data:

{
  recipename: "Cheese sandwich",
  description: "Who doesn't like a good cheese sandwich?",
  ingredients: ["bread", "cheese", "butter"],
  steps: ["<p>Step 1 is to spread the butter on the bread</p>", "<p>Step 2 is to put the cheese &quot;in&quot; the bread (not on top, or underneath)</p>"]
}

Gives this: 😋

More info - there are much clearer explanations of templates on the Mustache website. Try reading those pages "before" posting on stack overflow :) .

Blocks (Moodle 3.0 onwards)

Blocks are a feature of Mustache that deserves a special mention. The are used as a form of inheritance - and are crucial to building a library of re-usable templates. To make use of "blocks" you define a parent template with replaceable sections. Each of those sections is marked with a "blocks" tag like this (A blocks tag looks like a regular tag, but the variable name is preceded with $):

<section>
<h1>{{$sectionheading}}Default heading{{/sectionheading}}</h1>
<div>
{{$content}}Content for section{{/content}}
</div>
</section>

Now - wherever I need to re-use this template I can include it and replace the content of those sections at the same time.

{{< section}}
{{$sectionheading}}Latest News{{/sectionheading}}
{{$content}}Nothing happened today - sorry!{{/content}}
{{/section}}

Notice that when I include a template and I want to make use of blocks - the include tag points the other way:

{{< section}}

Not

{{> section}}

Blocks support looping and many other cool things - for more info see https://github.com/bobthecow/mustache.php/wiki/BLOCKS-pragma

Where do I put my templates?

Templates go in the <componentdir>/templates folder and must have a .mustache file extension. When loading templates the template name is <componentname>/<filename> (no file extension).

So "mod_lesson/timer" would load the template at mod/lesson/templates/timer.mustache.

Note: Do not try and put your templates in sub folders under the "/templates" directory. This is not supported and will not work.

How do I call a template from javascript?

Rendering a template from javascript is fairly easy. There is a new AMD module that can load/cache and render a template for you.

// This is AMD code for loading the "core/templates" module. see [Javascript Modules].
require(['core/templates'], function(templates) {
 
    // This will be the context for our template. So {{name}} in the template will resolve to "Tweety bird".
    var context = { name: 'Tweety bird', intelligence: 2 };
 
    // This will call the function to load and render our template. 
    templates.render('block_looneytunes/profile', context);
 
    // It returns a promise that needs to be resoved.
            .then(function(html, js) {
                // Here eventually I have my compiled template, and any javascript that it generated.
                // The templates object has append, prepend and replace functions.
                templates.appendNodeContents('.block_looneytunes .content', source, javascript);
            }).fail(function(ex) {
                // Deal with this exception (I recommend core/notify exception function for this).
            });
});


Under the hood, this did many clever things for us. It loaded the template via an ajax call if it was not cached. It found any missing lang strings in the template and loaded them in a single ajax request, it split the JS from the HTML and returned us both in easy to use way. Read on for how to nicely deal with the javascript parameter.

Note: with some nice chaining and sugar, we can shorten the above example quite a bit:

require(['core/templates', 'core/notification'], function(templates, notification) {
    var context = { name: 'Tweety bird', intelligence: 2 };
    templates.render('block_looneytunes/profile', context)
        .then(doneCallback)
        .fail(notification.exception);
});

What if a template contains javascript?

Sometimes a template requires that some JS be run when it is added to the page in order to give it more features. In the template we can include blocks of javascript, but we should use a special section tag that has a "helper" method registered to handle javascript carefully.

Example profile.mustache

<div id="profile">
<p>Name: {{name}}</p>
<p>Intelligence: {{intelligence}}</p>
</div>
{{#js}}
require('jquery', function($) {
    // Effects! Can we have "blink"?
    $('#profile').slideDown();
});
{{/js}}


If this template is rendered by PHP, the javascript is separated from the HTML, and is appended to a special section in the footer of the page "after" requirejs has loaded. This provides the optimal page loading speed. If the template is rendered by javascript, the javascript source will be passed to the "done" handler from the promise. Then, when the "done" handler has added the template to the DOM, it can call

templates.runTemplateJS(javascript);

which will run the javascript (by creating a new script tag and appending it to the page head).

What other helpers can I use?

{{# str }}

There is a string helper for loading language strings.

{{# str }} helloworld, mod_greeting {{/ str }}
The first 2 parameters are the string id and the component name. So this is effectively Mustache variant of
get_string('helloworld', 'mod_greeting')
. The optional third parameter defines the value for the string's
$a
placeholder:
{{# str }} iscool, mod_cool, David Beckham {{/ str }}
This example would effectively do what
get_string('iscool', 'mod_cool', 'David Beckham')
does in Moodle PHP code. Variable tags are allowed to define the value of the
$a
placeholder:
{{# str }} iscool, mod_cool, {{ name }} {{/ str }}

For strings that accept complex placeholder, see the following section.

{{# quote }}

As shown in the previous section, the
{{# str }}
helper may need complex data structures passed as the value of the
$a
placeholder. You can use a JSON object syntax in that case:
{{# str }} iscool, mod_cool, { "firstname": "David", "lastname": "Beckham" } {{/ str }}

If you wanted to use the context values instead of literal strings, you might intuitively use something like this:

{{! DO NOT DO THIS !}}
{{# str }} iscool, mod_cool, { "firstname": "{{ firstname }}", "lastname": "{{ lastname }}" } {{/ str }}
There is a potential problem though. If the variable tag
{{ firstname }}
or
{{ lastname }}
evaluates to a string containing the double quote character, that will break the JSON syntax. We need to escape the double quotes potentially appearing in the variable tags. For this, use the
{{# quote }}
helper:
{{! This is OK !}}
{{# str }} iscool, mod_cool, { "firstname":  {{# quote }}{{ firstname }}{{/ quote }}, "lastname": {{# quote }}{{ lastname }}{{/ quote }} } {{/ str }}

See MDL-52136 for details.

{{# pix }}

There is a pix icon helper for generating pix icon tags.

{{# pix }} t/edit, core, Edit David Beckham {{/ pix }}

The first 2 parameters are the string id and the component name, the rest is the alt text for the image.

{{# userdate }}

This mustache template helper will format unix timestamps into a given human readable date format while using the user's timezone settings configured (if any) in Moodle. The helper will accept hardcoded values, context variables, or other helpers.

The recommended way to use this helper is to use the string helper to get one of the core Moodle formats because they have been translated into other languages so you'll get multi-lang support for free (that's a pretty good deal!).

Using the string helper (recommended)

// Assuming we had a context variable named "time" set to 1293876000.
{{#userdate}} {{time}}, {{#str}} strftimedate {{/str}} {{/userdate}}

This will ask the Moodle server for the string "strftimedate" and will use the value (which in this case is "%d %B %Y") to format the user date. So the resulting formatted timestamp from the userdate helper will be "01 January 2011".

Using context variables

// Assuming we had a context variable named "time" set to 1293876000.
{{#userdate}} {{time}}, %A, %d %B %Y, %I:%M %p {{/userdate}}

Will produce "Saturday, 01 January 2011, 10:00 AM"

Using hardcoded values

{{#userdate}} 1293876000, %A, %d %B %Y, %I:%M %p {{/userdate}}

Will produce "Saturday, 01 January 2011, 10:00 AM"

{{# shortentext }}

This helper can be used to shorten a large amount of text to a specified length and will append a trailing ellipsis to signify that the text has been shortened.

The algorithm will attempt to preserve words while shortening to text. Words, for the purposes of the helper, are considered to be groups of consecutive characters broken by a space or, in the case of a multi-byte character, after the completion of the multi-byte character (rather than in the middle of the character).

It will also attempt to preserve HTML in the text by keeping the opening and closing tags. Only text within the tags will be considered when calculating how much should be truncated to reach the desired length.

The helper takes two comma separated arguments. The first is the desired length and the second is the text to be shortened. Both can be provided as context variables.

Plain text

{{#shortentext}} 30, long text without any tags blah de blah blah blah what {{/shortentext}}

Will produce:

long text without any tags ...

HTML text

{{#shortentext}} 30, <div class='frog'><p><blockquote>Long text with tags that will be chopped off but <b>should be added back again</b></blockquote></p></div></p> {{/shortentext}}

Will produce:

<div class='frog'><p><blockquote>Long text with tags that ...</blockquote></p></div>

Multi-byte text

{{#shortentext}} 6, 𠮟𠮟𠮟𠮟𠮟𠮟𠮟𠮟𠮟𠮟𠮟𠮟 {{/shortentext}}

Will produce:

𠮟𠮟𠮟...

How do I call a template from php?

The templates in php are attached to the renderers. There is a renderer method "render_from_template($templatename, $context)" that does the trick.

How do templates work with renderers?

Extra care must be taken to ensure that the data passed to the context parameter is useful to the templating language. The template language cannot:

  • Call functions
  • Perform any boolean logic
  • Render renderables
  • Do capability checks
  • Make DB queries

So - I have "some" data in my renderable and some logic and HTML generation in my render method for that renderable - how do I refactor this to use a template?

The first thing to note, is that you don't have to use a template if you don't want to. It just means that themers will still have to override your render method, instead of just overriding the template. But if you DO want to use a template, you will earn "cred" with themers, and you will be able to re-render parts of your interface from javascript in response to ajax requests without reloading the whole page (that's cool).

There is a simple pattern to use to hook a template into a render method. If you make your renderable implement templatable as well as renderable - it will have to implement a new method "export_for_template(renderer_base $output)". This method takes the data stored in the renderable and "flattens it" so it can be used in a template. If there is some nested data in the renderable (like other renderables) and they do not support templates, they can be "rendered" into the flat data structure using the renderer parameter. It should return an stdClass with properties that are only made of simple types: int, string, bool, float, stdClass or arrays of these types. Then the render method can updated to export the data and render it with the template.

In the renderable:

/**
     * Export this data so it can be used as the context for a mustache template.
     *
     * @return stdClass
     */
    public function export_for_template(renderer_base $output) {
        $data = new stdClass();
        $data->canmanage = $this->canmanage;
        $data->things = array();
        foreach ($this->things as $thing) {
            $data->things[] = $thing->to_record();
        }
        $data->navigation = array();
        foreach ($this->navigation as $button) {
            $data->navigation[] = $output->render($button);
        }
 
        return $data;
    }

In the renderer class:

/**
     * Defer to template.
     *
     * @param mywidget $widget
     *
     * @return string HTML for the page
     */
    render(mywidget $widget) {
        $data = $widget->export_for_template($this);
        return $this->render_from_template('mywidget', $data);
    }

How to I override a template in my theme?

Templates can be overridden a bit easier than overriding a renderer. First - find the template that you want to change. E.g. "mod/wiki/templates/ratingui.mustache". Now, create a sub-folder under your themes "templates" directory with the component name of the plugin you are overriding. E.g "theme/timtam/templates/mod_wiki". Finally, copy the ratingui.mustache file into the newly created "theme/timtam/templates/mod_wiki" and edit it. You should see your changes immediately if theme designer mode is on. Note: templates are cached just like CSS, so if you are not using theme designer mode you will need to purge all caches to see the latest version of an edited template. If the template you are overriding contains a documentation comment (see next section) it is recommended to remove it, it will still show the documentation in the template library.

Should I document my templates?

Yes!!!! Theme designers need to know the limits of what they can expect to change without breaking anything. As a further benefit - your beautiful new template can be displayed in the "Template Library" tool shipped with Moodle. In order to provide nice documentation and examples for the Template Library, you should follow these conventions when documenting your template.

Add a documentation comment to your template

Mustache comments look like this:

  {{! 
   I am a comment.
   I can span multiple lines.
  }}

The template library will look for a mustache comment that contains this special marker as the documentation to display, and the source of an example context.

@template component/templatename

Useful things to include in the documentation for a template

Classes required for JS

This is a list of classes that are used by the javascript for this template. If removing a class from an element in the template will break the javascript, list it here.

Data attributes required for JS

This is a list of data attributes (e.g. data-enhance="true") that are used by the javascript for this template. If removing a data attribute from an element in the template will break the javascript, list it here.

Context variables required for this template

This is a description of the data that may be contained in the context that is passed to the template. Be explicit and document every attribute.

Example context (JSON)

The Template Library will look for this data in your documentation comment as it allows it to render a "preview" of the template right in the Template Library. This is useful for theme designers to test all the available templates in their new theme to make sure they look nice in a new theme. It is also useful to make sure the template responds to different screen sizes, languages and devices. The format is a JSON-encoded object that is passed directly into the render method for this template.

A full example

lib/templates/pix_icon.mustache

  {{!                                                                                                                                 
    This file is part of Moodle - http://moodle.org/                                                                                
                                                                                                                                    
    Moodle is free software: you can redistribute it and/or modify                                                                  
    it under the terms of the GNU General Public License as published by                                                            
    the Free Software Foundation, either version 3 of the License, or                                                               
    (at your option) any later version.                                                                                             
                                                                                                                                    
    Moodle is distributed in the hope that it will be useful,                                                                       
    but WITHOUT ANY WARRANTY; without even the implied warranty of                                                                  
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                                                                   
    GNU General Public License for more details.                                                                                    
                                                                                                                                    
    You should have received a copy of the GNU General Public License                                                               
    along with Moodle.  If not, see <http://www.gnu.org/licenses/>.                                                                 
  }}                                                                                                                                  
  {{!                                                                                                                                 
    @template core/pix_icon                                                                                                         
                                                                                                                                    
    Moodle pix_icon template.                                                                                                       
                                                                                                                                    
    The purpose of this template is to render a pix_icon.                                                                           
                                                                                                                                    
    Classes required for JS:                                                                                                        
    * none                                                                                                                          
                                                                                                                                    
    Data attributes required for JS:                                                                                                
    * none                                                                                                                          
                                                                                                                                    
    Context variables required for this template:                                                                                   
    * attributes Array of name / value pairs.                                                                                       
                                                                                                                                    
    Example context (json):                                                                                                         
    {                                                                                                                               
        "attributes": [                                                                                                             
            { "name": "src", "value": "http://moodle.com/wp-content/themes/moodle/images/logo-hat2.png" },                          
            { "name": "class", "value": "iconsmall" }                                                                               
        ]                                                                                                                           
    }                                                                                                                               
                                                                                                                                    
  }}                                                                                                                                  
  <img {{#attributes}}{{name}}="{{value}}" {{/attributes}}/>

Coding style for templates

This section documents some coding style guidelines to follow when writing templates. The reason for these guidelines is to promote consistency, and interoperability of the templates.

Include GPL at the top of each template

Templates are a form of code and it is appropriate to license them like any other code.

Include a documentation comment for each template

The exception is when you are overriding a template, if the documentation from the parent still applies, you do not need to copy it to the overridden template.

Use data-attributes for JS hooks

Data attributes are ideal for adding javascript hooks to templates because:

  • Classes are meant for styling - theme designers should be able to change the classes at will without breaking any functionality.
  • IDs must be unique in the page, but it is not possible to control how many times the same template might be included in the page.
  • Data attributes can have meaningful names and can be efficiently queried with a selector

Avoid custom CSS for templates

This is not a hard rule, but a preference. We already have too much CSS in Moodle - where ever possible we should try and re-use the existing CSS instead of adding new CSS to support every new template.

Re-use core templates as much as possible

First we need to build the core set of reusable templates - but once that is in place we should always try to re-use those core templates to build interfaces. This will make Moodle more consistent, attractive and customisable.

Do use the CSS framework classes directly in the templates

We have bootstrap in core - so lets make the most of it. There is no problem using bootstrap classes in core templates, as long as the "base" theme is also tested, and an overridden template is added there if required.

Avoid IDs for styling or javascript

IDs should never evet be used for styling as they have a high CSS specificity, and so are hard to override. In addition, IDs should be unique in the page, which implies that a template could only be used once in a page. IDs are also not ideal for javascript, for the same reason (must be unique in a page).

The only acceptable case to use an ID is you need to create a one to one connection between the JS and template. In this case use the uniqid helper to generate an ID that will not conflict with any other template on the page, and use it as part of the ID.

<div id="{{uniqid}}-somethingspecific">
</div>
{{#js}}
    callFunction('{{uniqid}}-somethingspecific');
{{/js}}

Follow CSS coding style

https://docs.moodle.org/dev/CSS_coding_style

Use hyphens as word-separators for class names. Use lower case class names.

Wrap each template in one node with a classname that matches the template name

Generate a class name by combining the component and template names and separating words with underscore.

e.g.

<div class="core_user_header">
...
</div>

Iterating over php arrays in a mustache template

Mustache treats hashes and arrays differently because of cross language compatibility In php arrays and hashes are the same, but mustache treats them differently It decides a php array is a hash and will not iterate over it if it is non 0 indexed and/or has a gap in the key numbers so in short you need to

$datafortemplate->mylist =  array_values($myarraywithnonnumerickeys)

you could also use

$datafortemplate->mylist = new ArrayIterator($myarraywithnonnumerickeys);

BUT this fails when $myarraywithnonnumerickeys is empty and you try to use

{{#mylist}}
with an array iterator if mylist is empty this block will not run
{{/mylist}}
{{^mylist}}
with an array iterator mylist will not run this block either because it is not quite empty
{{/mylist}}

How do I write core templates?

Core templates should ideally be simple generic components that can be used within other templates to create more complex page layouts. They should be flexible enough for developers and themers to easily use without having to replace the template. The templates should attempt to encapsulate some core structure for the element as well as key classes while allowing the content to be easily overridden. Ultimately we want to avoid having duplicate HTML copied from template to template where possible, particularly if the HTML element has some classes associated with it.

Mustache relies on variables to substitute context data into the template but unfortunately it's very unlikely that the the names of the context data will match what the template is expecting for all the places that the template might be used. So in order to allow easy extensibility and avoid having to duplicate templates just to rename the variables we can wrap them in block variables which would allow the template that is including our template to replace that variable with one from it's own context inline.

There are a few key points to keep in mind when writing a core template:

  • Consider how your template will actually be used. Try writing a test page that uses your template to help discover some of the assumptions you might have in the template.
  • The example context you provide in the template is mostly just for showing the template in the template library and is likely not how your template will actually be used. Most uses of the template will have a different context all together.
  • Try to enforce a core structure but avoid enforcing a specific context. Content should be overridable.
  • Use block variables to indicate sections of your template that people are likely to want to change. Typically where they will be wanting to substitute in their own content.
  • Try to keep any javascript that accompanies the template as decoupled from the HTML / CSS structure of the template as possible. Instead of relying on the existence of certain HTML elements or CSS classes it is generally better to leverage data-attributes which can be added to any element.

An example: tabs

Let's go through an example to illustrate how you might build a core template. For the example we'll be building a tabs template, since it's a fairly complex component that requires the use of block variables and javascript.

First we can create a basic template to get the general structure down, let's call it tabs. Here's what it might look like:

<div id="{{ uniqid }}-tab-container">
    <ul role="tablist" class="nav nav-tabs">
		{{# tabs }}
			<li role="tab"
					data-target="{{ uniqid }}-{{ id }}"
					data-selected-class="active"
					aria-controls="{{ uniqid }}-{{ id }}"
					aria-selected="false" tabindex="-1">

				<a href="#">{{{ name }}}</a>
			</li>
		{{/ tabs }}
	</ul>
    <div class="tab-content">
		{{# tabs }}
			<div role="tabpanel"
				class="tab-pane"
				id="{{ uniqid }}-{{ id }}">

				{{{ content }}}
			</div>
		{{/ tabs }}
	</div>
</div>
{{#js}}
    require(['jquery','core/tabs'], function($, tabs) {

        var container = $("#{{ uniqid }}-tab-container");
        tabs.create(container);
    });
{{/js}}

The template requires a context that looks something like:

{
	"tabs": [
		{"id":"tab1","name":"Tab 1","content":"This is tab 1 content <a href=\"#\">test</a>"},
		{"id":"tab2","name":"Tab 2","content":"This is tab 2 content <a href=\"#\">test</a>"},
		{"id":"tab3","name":"Tab 3","content":"This is tab 3 content <a href=\"#\">test</a>"}
	]
}

The javascript required to power the tabs element (keyboard navigation, show / hide panels etc) is written as an AMD module and is included by the template. The javascript is a little too large to go through here, but some key points to consider when writing it are: It should ideally be independent of the HTML structure, so if someone wants to completely rewrite the tabs to be different elements (e.g. buttons or a set of divs) then the same javascript can be used without needing to change it. In order to achieve this it is important to identify the key components of the template.

In this case it is a tab list, a tab and it's content. One way to identify these components would be to inspect the structure of the DOM, for example you might say "find me the ul element" when looking for the tab list and then "find my the child li elements" to find the tabs. While this would work, it couples your javascript to the HTML structure and makes it difficult to change later. A different approach would be to use the element attributes, for example you might say "find my the element with the role 'tablist'" to get the tab list and then "find me the elements with the role 'tab'" to get the tabs. This allows the HTML structure to change without breaking the javascript (as long as the correct attributes are set, of course).

Another point of consideration for this example is what class to apply to a tab when it is selected. It makes sense to just apply something like "active" in the javascript, but that once again couples it to a particular CSS framework which makes it more difficult to change without modifying the javascript. In this case I chose to add a data attribute to the element to indicate which class will be set when the tab is selected. This means the javascript doesn't have to guess what the appropriate class is, it can just get it from the template.

Ok, so we've got our basic template. It's time to use it! Let's say we want to create a simple user profile page that might show 2 tabs, the first tab will be the user's name and the second tab will be the user's email address (please excuse the contrived example).

Here's what the page might look like:

<html>
    <header><title>User Profile</title></header>
    <body>
        {{< core/tabs }}
    </body>
</html>

That looks pretty simple! The only problem is, how do I get my content there? I would have to supply a context like this in order to display the tabs I want:

{
	"tabs": [
		{"id":"tab1","name":"Name","content":"Your name is Mr. Test User."},
		{"id":"tab2","name":"Email","content":"Your email is testuser@example.com"},
	]
}

Let's assume that the context for this page doesn't match what the tabs template is expecting though (as will be the case most of the time). Let's assume the tabs template is being rendered with this context:

{
	"name":"Mr. Test User",
	"email":"testuser@example.com"
}

Unfortunately, we'll almost certainly never have complete control over all of the contexts that our template will be rendered in which means we'll be expecting people to write new webservices to supply the same data in different formats every time they want to use a template. It becomes an unmanageable problem.

Enter blocks! We can make the template more flexible by defining sections of the template that can be overriden when they are included. Pretty neat! This will allow us to enforce a certain core structure but not enforce a context on the template that is including the tabs.

Let's have another go at that template, this time leverging blocks:

<div id="{{ uniqid }}-tab-container">
	{{$ tabheader }}
		<ul role="tablist" class="nav nav-tabs">
			{{$ tablist }}
				{{# tabs }}
					<li role="tab"
							data-target="{{ uniqid }}-{{ id }}"
							data-selected-class="active"
							aria-controls="{{ uniqid }}-{{ id }}"
							aria-selected="false" tabindex="-1">

						<a href="#">{{{ name }}}</a>
					</li>
				{{/ tabs }}
			{{/ tablist }}
		</ul>
	{{/ tabheader }}
	{{$ tabbody }}
		<div class="tab-content">
			{{$ tabcontent }}
				{{# tabs }}
					<div role="tabpanel"
						class="tab-pane"
						id="{{ uniqid }}-{{ id }}">

						{{{ content }}}
					</div>
				{{/ tabs }}
			{{/ tabcontent }}
		</div>
	{{/ tabbody }}
</div>
{{#js}}
    require(['jquery','core/tabs'], function($, tabs) {

        var container = $("#{{ uniqid }}-tab-container");
        tabs.create(container);
    });
{{/js}}

A summary of what we've changed:

  • Added a $tabheader block around the tab list, in case someone wants to change the ul element to something else.
  • Added a $tablist block around the group of tabs to allow them to be overriden on incldue.
  • Added a $tabbody block around the content, in case someone wants to change the content elements from divs.
  • Added a $tabcontent block around the tab variable for the content to allow the content to be overriden on inlcude.

Now let's see what using this template looks like for your User Profile page:

<html>
    <header><title>User Profile</title></header>
    <body>
        {{> core/tabs }}
			{{$ tablist }}
				<li role="tab"
						data-target="{{ uniqid }}-tab1"
						data-selected-class="active"
						aria-controls="{{ uniqid }}-tab1"
						aria-selected="false" tabindex="-1">

					<a href="#">Name</a>
				</li>
				<li role="tab"
						data-target="{{ uniqid }}-tab2"
						data-selected-class="active"
						aria-controls="{{ uniqid }}-tab2"
						aria-selected="false" tabindex="-1">

					<a href="#">Email</a>
				</li>
			{{/ tablist }}
			{{$ tabcontent }}
				<div role="tabpanel"
					class="tab-pane"
					id="{{ uniqid }}-tab1">

					Your name is {{ name }}.
				</div>
				<div role="tabpanel"
					class="tab-pane"
					id="{{ uniqid }}-tab2">

					Your email address is {{ email }}.
				</div>
			{{/ tabcontent }}
		{{/ core/tabs }}
    </body>
</html>

That looks a bit better! Now we've been able to use the blocks to successfully change the template to use the context available to this page, we no longer need a "tabs" array with "name" and "content". Even the javascript will continue to work because we've kept the correct element attributes.

We've still got a slight problem though... In order to change the data for the template we've had to copy & paste the HTML from the original template into our blocks as we do the override. While this works fine in this example, it means we don't quite get the encapsulation we want within the templates since we're leaking internal implementation details. If we ever wanted to change the CSS framework we use for Moodle (say from bootstrap 2 to boostrap 3 or 4) we'd have to find all the places in the code where this tabs template is used and make sure that the HTML is correct in their block overrides.

With that in mind, let's take one more pass at this template and see if we can improve it slightly again. This time we're doing to split the template out into 3 templates.

tabs.mustache:

<div id="{{ uniqid }}-tab-container">
	{{$ tabheader }}
		<ul role="tablist" class="nav nav-tabs">
			{{$ tablist }}
				{{# tabs }}
					{{< core/tab_header_item }}		
				{{/ tabs }}
			{{/ tablist }}
		</ul>
	{{/ tabheader }}
	{{$ tabbody }}
		<div class="tab-content">
			{{$ tabcontent }}
				{{# tabs }}
					{{< core/tab_content_item }}
				{{/ tabs }}
			{{/ tabcontent }}
		</div>
	{{/ tabbody }}
</div>
{{#js}}
    require(['jquery','core/tabs'], function($, tabs) {

        var container = $("#{{ uniqid }}-tab-container");
        tabs.create(container);
    });
{{/js}}

tab_header_item.mustache

<li role="tab"
		data-selected-class="active"
		aria-selected="false" tabindex="-1">

	<a href="#">{{$ tabname }}{{{ name }}}{{/ tabname }}</a>
</li>

tab_content_item.mustache

<div role="tabpanel"
	class="tab-pane"

	{{$ tabpanelcontent }}{{{ content }}}{{/ tabpanelcontent }}
</div>

A summary of the changes:

  • Split the template into 3, moving the tab into it's own template and the content into it's own and then including them in the tabs template.
  • Removed the ids from the tabs and content. The javascript would be updating to assign these ids at runtime so that they don't need to be provided as part of the template context.
  • Added a $tabname block for in the tab_header_item template to make the name flexible on import.
  • Added a $tabpanelcontant block in the tab_content_item template to make the content flexible on import.

Cool, so let's see what that looks like in our example now:

<html>
    <header><title>User Profile</title></header>
    <body>
        {{> core/tabs }}
			{{$ tablist }}
				{{> core/tab_header_item }}
					{{$ tabname }}Name{{/ tabname }}
				{{/ core/tab_header_item }}
				{{> core/tab_header_item }}
					{{$ tabname }}Email{{/ tabname }}
				{{/ core/tab_header_item }}
			{{/ tablist }}
			{{$ tabcontent }}
				{{> core/tab_content_item }}
					{{$ tabpanelcontent }}Your name is {{ name }}.{{/ tabpanelcontent }}
				{{/ core/tab_content_item }}
				{{> core/tab_content_item }}
					{{$ tabpanelcontent }}Your email address is {{ email }}.{{/ tabpanelcontent }}
				{{/ core/tab_content_item }}
			{{/ tabcontent }}
		{{/ core/tabs }}
    </body>
</html>

And we're done! After making the changes above we've been able to keep the benefits of the previous change to allow the context changes but we've also removed the need to copy & paste the HTML everywhere. Instead we're able to use the child templates with a few additional blocks defined to get the content in there.

Now if we want to change tabs HTML or CSS frameworks we can just change the core tabs templates and this page will receive the updates for free.