ZPT-JS reference - Format expressions

Syntax

format_expressions ::= 'format:' formatter expression format_arguments
formatter          ::= Name
format_arguments   ::= [expression]*
                

Description

Format expressions makes it easy to format values. They use formatters to do the work: a formatter is a normal function that must be previously registered. ZPT-JS includes some built-in formatters:

How are formatters found by ZPT-JS? When ZPT-JS finds a format expression it tries to locate the formatter following this order:

  1. First it tries to get it from the context. It uses the context.getFormatter() method to try to find it.
  2. If the formatter is not found, it tries to get it from the scope using the formatter as a function name.
  3. If the formatter is not found, it evaluates the formatter as an expression and then it tries to get it from the scope using the resulting value as a function name.
  4. If the formatter is not found, an exception is thrown.

You can add your custom formatters simply adding a function with the same name to the dictionary.

Differences with ZPT

Formatters does not exist in ZPT.

Examples

Simple format:

<div data-content="format: lowerCase 'Test'">must be test</div>
<div data-content="format: upperCase 'Test'">must be TEST</div>
                

Format with arguments:

<div data-content="format: fix 1.377 2">must be 1.37</div>
<div data-content="format: fix (/: 1 3) 2">must be 1.33</div>
                

Custom formatters using dictionary

The javascript code:

"use strict";

var zpt = require( 'zpt' );

// To register customFormatter add it to the dictionary
var dictionary = {
    myCustomFormatter: function( value ){
        return "$" + value;
    }
};

// Parse template
zpt.run({
    root: document.body,
    dictionary: dictionary
});
                

...and the invokation of myCustomFormatter:

<div data-content="format: myCustomFormatter 1.55">must be $1.55</div>
                

Custom formatters using context

The javascript code:

"use strict";

var zpt = require( 'zpt' );

var dictionary = {};

// To register customFormatter add it to the context
zpt.context.registerFormatter( 
    'customFormatter', 
    function( value ){
        return "$" + value;
    }
);

// Parse template
zpt.run({
    root: document.body,
    dictionary: dictionary
});
                

...and the invokation is exactly equal.