overtemplate

Filters

Built-in Filter Reference Index

Note: null may be substituted for optional parameters, parentheses are optional if no parameters are needed.
Note: Literal strings like "this" are used as the expression for the examples in the following sections. Any valid expression is equally suitable such as person.name or list[4].description

escape

Converts the input to a string and encode the four critical entities characters &, <, > and " into entities.

Template: "Mom & Pop" | escape
Output: Mom &amp; Pop

Normally used in the non-encoding interpolation tag (<%=) since the escape tag already will encode HTML entities.

trim

Removes leading and trailing.

Template: " has space around it " | trim
Output: has space around it

Whitespace as defined by the javascript RegExp \s assertion. See: Whitespace as defined by the javascript RegExp \s assertion. See: ECMAScript 2022 Language Specification

normalize

Syntax: normalize([sub])

Remove leading and trailing space and reduce any sequences of consecutive whitespace into a single space character or other string if specified.

Template: " has space around it " | normalize
Output: has space around it

Template: " has space around it " | normalize("⎡GLUE⎤")
Output: has⎡GLUE⎤space⎡GLUE⎤around⎡GLUE⎤it

Whitespace as defined by the javascript RegExp \s assertion. See: ECMAScript 2022 Language Specification

pad

Syntax: pad( length; [char]; [side])

Lengthen a string to the specified length by concatenating characters, by default a space, to the start, end or both sides of the input string to a specified length. char is a space by default and characters are added to the end (right side) of the string. If the input string already length characters long or longer, no change is made. both and center are synonymous.

Template: "blue" | pad(10)
Output: blue      

Template: "apple" | pad(15;" -";"both")
Output: - - apple - -

trunc

Syntax: trunc( length; [side]; [ellipsis-char])

Shorten a string to the specified length by removing characters from the start, end or both sides of the input string to a specified length. By default, characters are removed from the end (right side) of the string. A side value of ellipsis is similar to end but replaces the last character with the ellipsis character or other specified character if the string is truncated. both and center are synonymous.

Template: "abcdefghijklmnopqrstuvwxyz" | trunc(16)
Output: abcdefghijklmnop

Template: "whitespace is preserved" | trunc(13;"center")
Output: space is pres

Template: "whitespace is preserved" | trunc(13;"ellipsis")
Output: whitespace i…

Template: "whitespace is preserved" | trunc(13;"ellipsis";"@")
Output: whitespace i@

fit

Make a string fit a specific length adding or removing characters as needed. fit is equivalent to using both pad and trim with the same length.

Syntax: fit( length; [char]; [side]; [ellipsis-char])

Template: "whitespace is preserved" | fit(13;null;"center")
Output: space is pres

Template: "whitespace is preserved" | fit(32;"#";"center")
Output: ####whitespace is preserved#####

Template: "whitespace is preserved" | fit(13;null;"ellipsis";"Ⓧ")
Output: whitespace iⓍ

lowerCase

Convert characters in a string to lowercase according to the current locale. See: toLocaleLowerCase on MDN

Template: "Are you for SCUBA?" | lowerCase Output: are you for scuba?

upperCase

Convert characters in a string to uppercase according to the current locale. See: toLocaleLowerCase on MDN

Template: "we're not going to take it!" | upperCase Output: WE'RE NOT GOING TO TAKE IT!

capitalize

Convert the first character of a string to uppercase and optionally convert the other characters of a string to lowercase.

Syntax: capitalize or capitalize( [force])

Template: "billieBob is COOL" | capitalize
Output: BillieBob is COOL

Template: " billieBob is COOL " | capitalize(true;true)
Output: Billiebob is cool

wrapWith

Concatenate strings to the start, end or both sides of a string optionally inserting another string (glue) in between.

Syntax: wrapWith([start]; [end]; [glue])

Template: "blue" | wrapWith("light")
Output: lightblue

Template: "blue" | wrapWith(null; "green")
Output: bluegreen

Template: "Amsterdam" | wrapWith("New"; null; " ")
Output: New Amsterdam

Template: "person" | wrapWith("parent"; "child"; ".")
Output: parent.person.child

Normally used in the non-encoding interpolation tag (<%=) since the escape tag already will encode HTML entities.

htmlWrap

Place input string in a properly formatted HTML tag.

Syntax: htmlWrap([tag]; [classes]; [style]; [raw]; [id])

Note: because css styles often contain a semicolon characters and those conflict with the default parameter separator any %3B character sequences will be replaced with semicolon characters in the style parameter value.

Template: "Mom & Pop" | htmlWrap
Output: <div>Mom &amp; Pop</div>

Template: "Mom & Pop" | htmlWrap("p";"active special";"color: blue";false;"primary")
Output: <p id="primary" class="active special" style="color: blue">Mom &amp; Pop</p>

Template: "contents" | htmlWrap("p") | htmlWrap("section"; false; false; true) Output: <section><p>contents</p></section>

Template: "bold and green" | htmlWrap("span";null;"font-weight: bold%3b color: green%3B")
Output: <span style="font-weight: bold; color: green;">bold and green</span>

Normally used in the non-encoding interpolation tag (<%=) since the escape tag already will encode HTML entities.

colorWrap

A convenience function similar to htmlWrap for creating an HTML tag with a color style.

Syntax: colorWrap([color]; [tag]; [classes]; [style]; [raw]; [id])

Template: errors[0].message | colorWrap('red';'p')
Data: {errors:[{code:17,message:"Error: unexpected failure"},{code:4,message:"Error: none"}]}
Output: <p style="color:red;">Error: unexpected failure</p>

Normally used in the non-encoding interpolation tag (<%=) since the escape tag already will encode HTML entities.

A convenience function similar to htmlWrap for creating an HTML anchor tag, the input string is used as the URL (href) for the anchor.

Syntax: htmlLink([linkText]; [target]; [classes]; [style]; [raw]; [id])

Template: search_engines[0].url | htmlLink(search_engines[0].name)
Data: {search_engines:[{url:"https://google.com",name:"Google"},{url:"https://bing.com",name:"Bing"}]} Output: <a href="https://google.com">Google</a>

Normally used in the non-encoding interpolation tag (<%=) since the escape tag already will encode HTML entities.

round

Round input number to specified number of decimal digits.

Syntax: round(digits)

Template: 123.7002107 | round(3) Output: 123.7

fixed

Round input number to specified number of decimal digits and format as a string with 0 padding to the right of the decimal point.

Syntax: fixed(digits)

Template: 123.7002107 | fixed(3) Output: 123.700

pick

Return an item from a string, array or object by index or property name.

Syntax: pick(index)

Examples: Data: {n: 3, list: [101,102,103,104,105], obj: {d:'Dog', c:'Cat', m: 'Monkey'}}

Template: "ABCDEFGHIJKLM" | pick(10)
Output: K

Template: "ABCDEFGHIJKLM" | pick(30; "n/a")
Output: n/a

Template: list | pick(n)
Output: 104

Template: obj | pick("m";"Bird")
Output: Monkey

toNumber

Coerce value to a number using the Number constructor.

Template: "123.5670000" | toNumber
Output: 123.567

See: Number constructor on MDN

toFloat

Coerce value to a number using the parseFloat function.

Template: "123.5670000" | toFloat
Output: 123.567

Template: " 71.39 ft " | toFloat
Output: 71.39

Note:

See: Number constructor on MDN

toInteger

Coerce value to a number using the parseInt function.

Template: "123.5670000" | toInteger
Output: 123

Template: "177.3 hours" | toInteger
Output: 177

Template: " 71.39 mm " | toInteger
Output: 71

See: See: Number constructor on MDN

toDate

Coerce value into a date using the Date constructor.

Examples:

Template: 1234567890000 | toDate Output: 2/13/2009, 4:31:30 PM

Template: '1980/2/25' | toDate Output: 2/25/1980, 12:00:00 AM

See: Date Constructor

msToDate

Shorthand for | toInteger | toDate

Syntax: msToDate(radix)

Examples:

Template: "1234567890000" | msToDate Output: 2/13/2009, 4:31:30 PM

Template: "11f71fb0450" | msToDate(16) Output: 2/13/2009, 4:31:30 PM

asDate

Convert a Date object to a string as the Date method toDateString() would. The Date constructor is used to coerce values to a Date object.

Examples:

Template: '1980/2/25' | toDate | asDate Output: Mon Feb 25 1980

See: toDateString on MDN

asTime

Convert a Date object to a string as the Date method toTimeString() would. The Date constructor is used to coerce values to a Date object.

Examples:

Template: '1980/2/25 1:12:11 pm' | toDate | asTime Output: 13:12:11 GMT-0700 (Mountain Standard Time)

See: toDateString on MDN

hex

Convert numeric value to hexadecimal as a string with an optional prefix.

Syntax: hex([prefix]; [upperCase])

Template: 3833585 | hex
Output: 3a7ef1

Template: 3833585 | hex("0x"; true)
Output: 0x3A7EF1

rot13

Encrypt string value with rot13 algorithm

Syntax: rot13

Template: "Abracadabra" | rot13
Output: Noenpnqnoen

Template: "Uryc! V'z orvat uryq cevfbare va n sbeghar pbbxvr snpgbel!" | rot13
Output: Help! I'm being held prisoner in a fortune cookie factory!

slice

Perform a slice operation on an array-like value

Syntax: slice(start; [end])

Template: items | slice(5;9) Data: {items: ['a','b','c','d','f','g','h','i','j']} Output: g,h,i,j

Template: items | slice(-5) Data: {items: ['a','b','c','d','f','g','h','i','j']} Output: f,g,h,i,j

See: slice on MDN

join

Perform a join operation on an array-like value returning a string

Syntax: join([separator];[last-separator])

Template: items | join('-') Data: {items: ['a','b','c','d']} Output: a-b-c-d

Template: items | join('•') Data: {items: ["red", "white", "blue"]} Output: red•white•blue

Template: items | join(', '; ' and ') Data: {items: ["red", "white", "blue"]} Output: red, white and blue

substr

Perform a slice operation on an array-like value

Template: "not kidding" | substr(4;3) Output: kid

Template: "not kidding" | substr(4) Output: kidding

See: slice on MDN

Custom Filters

Custom filters can be implemented with a javascript function. The first parameter passed to the filter function is the value form the expression or the output of the previous filter. The filter function is also bound (as this) to an object with the following properties:

Example Custom Filters

Simple Example

function bold (str) {
    return `<b>${str}</b>`;
}

template = '<%= v | bold %>',
compiled = overtemplate(template, {filters: {bold: bold}});
console.log(compiled({v: 'test'}));

####### Simple Example Output

<b>test</b>

Example With Parameter

function copies (value, count) {
  return Array((count || 10) + 1).join(`${value}`);
}

template = '<%= char | copies(values[2]) %>';
compiled = overtemplate(template, {filters: {copies: copies}});
console.log(compiled({char: '=', values: [13,22,11,17,8]}));

####### Simple Example Output

===========

Complex Example

const ESCAPE_ENTITIES = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#x27;', // eslint-disable-line quotes
    '`': '&#x60;',
};

function escapeHTML(str) {
    let pattern = '(?:' + Object.keys(ESCAPE_ENTITIES).join('|') + ')',
        testRegExp = new RegExp(pattern),
        replaceRegExp = new RegExp(pattern, 'g');

    if (testRegExp.test(str)) {
        return str.replace(replaceRegExp, function(match) {
            return ESCAPE_ENTITIES[match];
        });
    }
    return str;
}

function showExpression (str, showData) {
    let html = '<table><tr><th>Type</th><th>Value</th></tr>\n';
    html += `<tr><td>Expression</td><td>${escapeHTML(this.expression)}</td></tr>\n`;
    if (showData) {
        let data = escapeHTML(JSON.stringify(this.data, null, 2));
        html += `<tr><td>Data</td><td>${data}</td></tr>\n`;
    }
    html += `<tr><td>Value</td><td>${escapeHTML(str)}</td></tr>\n`;
    html += '</table>';
    return html;
}

template = '<%= people[1].name | show %>';
compiled = overtemplate(template, {filters: {show: showExpression}});
console.log(compiled({people:[{name:"Bob",age:31},{name:"Sally",age:27}]}));

See: ROT13 on wikipedia

####### Simple Example Output

<table><tr><th>Type</th><th>Value</th></tr>
<tr><td>Expression</td><td> people[1].name | show </td></tr>
<tr><td>Value</td><td>Sally</td></tr>
</table>