🐁 Schema-based mustache-like template compiler (work in progress; mainly for my own purposes)
import m from "mousetache";
const shape = m.object({
people: m.array(m.object({
name: m.terminal(),
address: m.terminal(),
}))
});
const source = `Say hello to:
{{#people}}- {{name}} {{#address}}({{.}}){{/address}} {{! parentheses only show if address is present}}
{{/people}}`;
const template = m.compile(source, shape);
console.log(template.render(
[
{ name: "Tom and Jerry" },
{ name: "Mickey Mouse", address: "Mickey's House" }
]
))
// Output:
// Say hello to:
// - Tom and Jerry
// - Micky Mouse (Mickey's House)Shapes are declared in a similar way to zod, but much simpler:
objecttakes a JavaScript object of{ key: shape }. Templates can access the propeties by their name.arraytakes a Shape to represent expected values for each item. Templates can access items by their index, as well as length.terminalrepresents anything. Templates can only insert the string value - properties can not be accessed and they must be the last segment of a key (hence the name).
The reason for this simplicity is because shapes are only used for the compiler, not for validating the passed data. They allow for simpler generated code and validation of the template itself. They also allow only exposing parts of objects.
Implements the following mustache features:
var&var#section^section- Overriding delimeters e.g.
={ }=to use{my_tag}
I wanted to use handlebars.js for configuration but its complexity seemed to lead to quite a few vulnerabilities. Mustache seemed nice and simple but none of the implementations seemed ideal for my use-case (allowing users to write custom templates).
Will anyone use this? probably not lol