Using Trimpath - JavaScript Templates

Trimpath is a very old template system, Base22 uses dust.js in the current XWidget version (3.x).

What are JavaScript Templates?
Javascript templates are a fast and efficient way for producing an HTML result from JSON object data.
The template used is written in HTML markup where tags are included. This JavaScript tags can be used to insert variables or even run some logic.
The templates are rendered and cached in the clients browser (client-side) and this allows a faster processing because we avoid an HTTP request to the server.

In Base22 we use Trimpath as the main JavaScript Templating

So, how is Trimpath used?

1. Calling the trimpath file

The first step is including trimpath into the html header:

	<script type="text/javascript" src="jquery-1.7.min.js"></script>
	<script type="text/javascript" src="trimpath-template-1.js"></script>

2. Creating the JSON object

After this, the JSON object should be created and added to the html file (If you do not know much about JSON, I suggest this quick and simple introduction into it: JSON introduction) . This can be done by adding the following script inside the html head:

	var json = {
			"color":"Dark Brown"

Another way of doing this is adding the above code (without the <script> opening and ending tags) into a .JS file and pulling it as a separate file. If the JSON object is really big, this is a better option for a better maintenance of the object and the html file itself.

	<script type="text/javascript" src="jsonObject.js"></script>

3. Understanding the Trimpath processing.

Trimpath needs two things in order to work properly.
1. The template to be used.
2. The JSON object to be processed by the template.

There are three ways for calling the Trimpath processing:
1. One line processing through Trimpath.

    var resultingHTML = TrimPath.processDOMTemplate("div#id", json);

Where "div#id" stands for the DIV which holds the template HTML to be used, and
"json" stands for the JSON object created previously.

So in this moment, the variable resultingHTML holds the HTML with the results that the template/json have delivered.
This variable ("resultingHTML") should now be appended to another div in the html.

2. Using the .process() method:

  var data = $('#tableContainer_jst').data('template').process(json);

In this example, we use jQuery to fetch the div with "tableContainer_jst" ID and get the DATA attr. (which holds a string with the HTML template). I'll explain this 'hack' at the end.
After getting the HTML template, call the process method, with the JSON object created in step 2.

This will return the resulting HTML to be appended to the div, just as var = resultingHTML did in the 1st example.

3. Using AJAX.
The third

//Through AJAX
  		var widgetData;

			url: "table.tpl.html",
			mimeType: 'application/json', // fixes the bug where firefox thinks this should be xml and throws console error on && in the tpls.
			dataType: 'text',
			async: false }) // sets to async: false because the tpl MUST be loaded before we proceed.
				.error( function() {
				.success( function(tplText) {

					try { 
						widgetData = tplText.process( json, {throwExceptions:true,keepWhitespace:false} );								
					} catch (err) { 
						console.log("some error! ");			
					}//end catch
		} ); //end ajax

4. Using the JSON object.

When the template receives the JSON object the correct way to navigate thru is the following:


Note: The json object name should NOT be included. I.E taking the above JSON object, we should not call it this way: json.person, json.animal, etc.

5. Learning to create the template.

There are a lot of options to use in a template. Some examples:

Using the dollar sign($) before the brackets will print whatever comes out from the brackets.
Print Variable

${json.age} => will write the value for the variable

Variable Assignment

{var hello = "Hello from Trimpath"} => will create a new variable named "hello" if the variable is ALREADY created and we want to reassign its value, we should again state "var hello" as follows:
{var hello = hello+" ...again!"}

Logical Statement
For Loop

{for p in person}
   //do something
   //do something

If Statement

{if person.age == 25}
   //do something
{elseif person.age == 24}
  //do something
  //do something


{if x != p && p == q}
{if x > p}
{if x < p}

Variable Assignment with logical statement

{var data = data1 != null ? data1 : "Final Data"}

6. Executing JS inside of Trimpath context

This is especially useful whenever you want to do some extra manipulation on the data inside of the tpl file before rendering it (creating arrays, json objects, modifying variables, etc).

eval blocks

    ...javascript evaluated during JST processing...

  {eval EOF}
    ...javascript evaluated during JST processing...

The EOF can be any text without a close-brace ('}') character.

The {eval} markup block can be useful to define multi-line JavaScript event handler functions near where they are used.

  <select onchange="sel_onchange()"></select>
    sel_onchange = function() {
     ...Do some complicated javascript...;
     ...more js code here...;

Note in the above example that the 'var' keyword is not used, like 'var sel_onchange = function() {...}'. This is to ensure that sel_onchange will be in global scope and hence usable as an event handler function.

About the author