README
Roll your own Mustache-like plaintext template language with custom syntax and template directives.
var plaintemplate = require('plaintemplate')
var assert = require('assert')
var processor = plaintemplate(
// Template directive handler
function handler(token, context, stringify) {
var directive = token.tag.trim()
// Repeate a tag's contents five times.
if (directive.startsWith('five')) {
var output = ''
for (var counter = 0; counter < 5; counter++) {
output += stringify(token.content, context, handler)
}
return output
// Insert a string from context.
} else if (directive.startsWith('=')) {
var key = directive.split(' ')[1]
return context[key]
} else throw new Error('Invalid directive')
},
// Use custom double-parentheses template tags.
{open: '((', close: '))', start: '{', end: '}'}
)
processor(
// Template input
'(( five { ))Howdy, (( = name ))! (( } ))',
// Context
{name: 'John'},
// Callback
function (error, result) {
assert.deepStrictEqual(
result,
'Howdy, John! ' +
'Howdy, John! ' +
'Howdy, John! ' +
'Howdy, John! ' +
'Howdy, John! '
)
}
)
The package exports a single function of two arguments:
Tag Hangler, optional (omit with
undefined
), a function of three arguments:Token, the plaintemplate-parse tag token object to stringify
Context, the context in which the token is to be stringified
Stringify, a function used to recursively stringify other plaintemplate-parse tokens, of three arguments:
Content, an array of plaintemplate-parse text and tag token objects, probably a tag token's content property
Context
Tag Handler
Callback, an error-first function
Parser Options, optional, an object, passed directly to plaintemplate-parse
The function returns another function of three arguments:
Input, a string, containing template text and tags
Context, an object, containing values that affect the template
Callback, an error-first function yielding the result of template processing
The default tag handler defines a number of template tag directives:
insert X
. Replaces a tag with the value ofX
in context. Throws an error ifX
does not exist in context.if X
. Renders the tag's contents only ifX
exists in context and has a "truthy" value. Throws an error ifX
does not exist in context.unless X
. Renders the tag's contents only ifX
exists in context and has a "falsey" value. Throws an error ifX
does not exist in context.each X
. Renders the tag's contents once for every array element ofX
in context. Throws an error ifX
does not exist in context, or ifX
exists in context, but is not an array. Sets a number of additional variables in context when rendering the tag's contents:element
, the array element being renderedodd
, if the index of the element in the array (counting from 1) is oddeven
, if the index of the element in the array (counting from- is even
first
, true if the element is the first element of the arraylast
, true if the element is the last element of the array