Skip to content

Partial implementation of the mustache template language for XQuery

Notifications You must be signed in to change notification settings

james-jw/xq-mustache

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

21 Commits
 
 
 
 
 
 

Repository files navigation

xq-mustache

Partial implementation of the mustache template language for XQuery 3.1.

See Mustache.js for details.

Whats implemented

  • Variables
  • Conditionals
  • Sections
  • Inversions
  • Compilation
  • Lambdas

Installation

You can use xqpm to install itself!

xqpm xq-mustache

Namespace

http://xq-mustache

Dependencies

None

Methods

This module includes three simple methods in the spirit of Mustache: render, compile and is-mustache.

render

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 

compile

Compiling a template is as easy as calling the following:

compile($template as item()) as element(fn:analyze-string-result) 

is-mustache

To check if a string contains a mustache expression simply use:

is-mustache($string as xs:string) as xs:boolean

Usage

Import into your XQuery module or script and call render providing a template and hash.

Basic

import module namespace mustache = 'http://xq-mustache';
let $hash := map { 'word': 'world' }
return
  mustache:render('Hello {{word}}!', $hash) 

Compiling

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

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)

Unit Tests

If using BaseX, unit tests can be run from BaseX via the command line:

basex -t src/xq-mustache-test.xqm

Shout Out!

If you like what you see here star the repo and or find me on github or linkedIn

Happy templating!

About

Partial implementation of the mustache template language for XQuery

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages