Creating custom dojox.dtl filters

Tags:

Dojo’s implementation of the Django Template Language (DTL) is pretty convenient for client-side templating in Dojo applications.

However, sometimes you need to customize formatting of values, or add other custom logic to it. Using a filter for this purpose is quite convenient, but Dojo’s implementation is completely undocumented as to how you would add your own.

Turns out it’s actually quite easy.

Step 1: Create a filter

All DTL filters in dojo follow a convention like below:

dojo.provide('my.dtl.filter.examples');
 
dojo.mixin(my.dtl.filter.examples, {
    exampleFilter: function(value) {
        //do something with value and return the result
        return value + 1;
    }
});

Doing this, we have a filter called exampleFilter, which adds 1 to a value passed to it, for example..

    <p>{{ someVal|exampleFilter }}</p>

The output of the template above would be the value of someVal with 1 added to it.

Step 2: Register your filter

To register our custom filter(s) with dojo…

dojox.dtl.register.filters('my.dtl.filter', { examples: ['exampleFilter'] });

In other words, you pass the base namespace as the first parameter, and then an object containing the filters.

In the object, the key should be the name of the object containing the filters, like ‘examples’ in our case, and the value should be an array with names of filter functions contained in the object in it.

Step 3: Profit

You’re done. Enjoy your shiny new custom dojox.dtl filter!

Adding custom tags works in a similar fashion, however implementing them is a bit more complicated. Refer to the built in tags to find out how to do it. To register tags, simply use dojox.dtl.register.tags instead of dojox.dtl.register.filters