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 asperson.name
orlist[4].description
Converts the input to a string and encode the four critical entities characters &
, <
, >
and "
into entities.
Template: "Mom & Pop" | escape
Output: Mom & Pop
Normally used in the non-encoding interpolation tag (<%=
) since the escape tag already will encode HTML entities.
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
Syntax: normalize([sub])
sub
- [optional] character to use in place of whitespace sequences, default:
(space)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
Syntax: pad( length; [char]; [side])
length
- [required] desired length of stringchar
- [optional] character(s) to be added to string if needed, default: ' '
side
- [optional] start
, end
, both
or center
default: 'end'
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 - -
Syntax: trunc( length; [side]; [ellipsis-char])
length
- [required] desired length of stringside
- [optional] start
, end
, both
, center
or ellipsis
default: 'end'
ellipsis-char
- [optional] character appended to indicate truncation occurred, default: …
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@
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])
length
- [required] desired length of stringchar
- [optional] character(s) to be added to string if needed, default: ' '
side
- [optional] start
, end
, both
, center
or ellipsis
default: 'end'
ellipsis-char
- [optional] character appended to indicate truncation occurred, default: …
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Ⓧ
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?
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!
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])
force
- [optional] a truthy value causes lowercasing of characters after the firstTemplate: "billieBob is COOL" | capitalize
Output: BillieBob is COOL
Template: " billieBob is COOL " | capitalize(true;true)
Output: Billiebob is cool
Concatenate strings to the start, end or both sides of a string optionally inserting another string (glue
) in between.
Syntax: wrapWith([start]; [end]; [glue])
start
- [optional] string to prepend, default: empty stringend
- [optional] string to append, default: empty stringglue
- [optional] string to place between input and non-empty concatenated stringsTemplate: "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.
Place input string in a properly formatted HTML tag.
Syntax: htmlWrap([tag]; [classes]; [style]; [raw]; [id])
tag
- [optional] html tag name, default: div
classes
- [optional] contents of class attribute, default: empty stringstyle
- [optional] contents of style attribute, default: empty stringraw
- [optional] truthy value prevents HTML entity escaping, default: false
id
- [optional] contents of id attribute, default: empty stringNote: 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 & Pop</div>
Template: "Mom & Pop" | htmlWrap("p";"active special";"color: blue";false;"primary")
Output: <p id="primary" class="active special" style="color: blue">Mom & 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.
A convenience function similar to htmlWrap for creating an HTML tag with a color style.
Syntax: colorWrap([color]; [tag]; [classes]; [style]; [raw]; [id])
color
- CSS color style property valueTemplate: 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])
linkText
- text used as the content on the anchor tag, if null
or undefined the URL is used insteadtarget
- string used as the target attribute of the anchor tagTemplate: 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 input number to specified number of decimal digits.
Syntax: round(digits)
digits
- number of decimal digits to the right of the decimal pointTemplate: 123.7002107 | round(3)
Output: 123.7
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)
digits
- number of decimal digits to the right of the decimal pointTemplate: 123.7002107 | fixed(3)
Output: 123.700
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
Coerce value to a number using the Number
constructor.
Template: "123.5670000" | toNumber
Output: 123.567
See: Number constructor on MDN
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
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
Coerce value into a date using the Date constructor.
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
Shorthand for | toInteger | toDate
Syntax: msToDate(radix)
radix
- number base used to interpret numeric string, default: 10 (decimal)Examples:
Template: "1234567890000" | msToDate
Output: 2/13/2009, 4:31:30 PM
Template: "11f71fb0450" | msToDate(16)
Output: 2/13/2009, 4:31:30 PM
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
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
Convert numeric value to hexadecimal as a string with an optional prefix.
Syntax: hex([prefix]; [upperCase])
prefix
- string to concatenate on the front (prepend) to the hexadecimal digitsupperCase
- truthy values cause the hexadecimal digits to be uppercaseTemplate: 3833585 | hex
Output: 3a7ef1
Template: 3833585 | hex("0x"; true)
Output: 0x3A7EF1
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!
Perform a slice operation on an array-like value
Syntax: slice(start; [end])
start
- index to start extraction, negative values from the end, default: 0end
- index to end extraction, negative values from the end, null for all items, default: nullTemplate: 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
Perform a join operation on an array-like value returning a string
Syntax: join([separator];[last-separator])
separator
- string to place between itemslast-separator
- string to place between the last two itemsTemplate: 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
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 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:
value
- the original expression value (before being transformed by any previous filters)data
- the current data model passed to the template function with changes from any loops in scopesettings
- the current settingsexpression
- the raw text of the expression excluding any filtersfunction 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>
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
===========
const ESCAPE_ENTITIES = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''', // eslint-disable-line quotes
'`': '`',
};
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>