Partial implementation of the mustache template language for XQuery 3.1.
See Mustache.js for details.
- Variables
- Conditionals
- Sections
- Inversions
- Compilation
- Lambdas
You can use xqpm to install itself!
xqpm xq-mustache
http://xq-mustache
None
This module includes three simple methods in the spirit of Mustache: render
, compile
and is-mustache
.
The render method can take a raw string or compiled expression and returns a rendered string.
render($template as item(), $hash as map()) as xs:string
Compiling a template is as easy as calling the following:
compile($template as item()) as element(fn:analyze-string-result)
To check if a string contains a mustache expression simply use:
is-mustache($string as xs:string) as xs:boolean
Import into your XQuery module or script and call render
providing a template and hash.
import module namespace mustache = 'http://xq-mustache';
let $hash := map { 'word': 'world' }
return
mustache:render('Hello {{word}}!', $hash)
If the template is going to be used multiple times you can increase performance significantly by compiling the expression:
import module namespace mustache = 'http://xq-mustache';
let $hash := map { 'word': 'world' }
let $compiled := mustache:compile('Hello {{word}} {{index}}!')
return
for $i in (1 to 1000)
return
mustache:render($compiled, (map { 'index': $i }, $hash))
Lambdas allow for powerful patterns such as wrapping. For example, the following would return
Hello World!
let $template := '{{#greeting}}{{name}}{{/greeting}}'
let $hash := map {
'name': 'world',
'greeting': function ($template, $hash) {
'Hello ' || mustache:render($template, $hash) || '!'
}
}
return
mustache:render($template, $hash)
If using BaseX, unit tests can be run from BaseX via the command line:
basex -t src/xq-mustache-test.xqm
If you like what you see here star the repo and or find me on github or linkedIn
Happy templating!