Last active
September 12, 2022 20:04
-
-
Save cowboyd/832989c6021c2fe06f86a0e4432ac558 to your computer and use it in GitHub Desktop.
Use nunchucks to render a precompiled template that doesn't require a `window` object or any global variables.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// requires deno > 1.25.1 | |
// deno run --allow-env --unstable nunjucks.ts | |
import nunjucks from "npm:nunjucks"; | |
// we use nunjucks itself to create the wrapper function | |
let wrapperFn = nunjucks.compile(` | |
(function() { | |
return function appendTemplates(precompiled) { | |
{% for template in templates %} | |
precompiled["{{template.name | safe}}"] = (function() { {{template.template | safe}} })() | |
{% endfor %} | |
return precompiled; | |
} | |
})(); | |
`); | |
let wrapper = templates => wrapperFn.render({ templates }); | |
// define the "salutations" module which has a `greet()` macro | |
let greet = nunjucks.precompileString(` | |
{% macro greet(name) %} | |
Hello {{name}} | |
{% endmacro %} | |
`, { | |
name: "salutations", | |
wrapper, | |
}); | |
// use the greet macro | |
let hello = nunjucks.precompileString(` | |
{% from "salutations" import greet %} | |
{{greet(name)}} | |
`, { | |
name: "hello.tmpl", | |
wrapper, | |
}); | |
let precompiled = {}; | |
//our custom wrapper returns a function that receives the record | |
//of global template modules. | |
eval(greet)(precompiled); | |
eval(hello)(precompiled); | |
let environment = new nunjucks.Environment([new nunjucks.PrecompiledLoader(precompiled)]) | |
console.log(environment.render("hello.tmpl", { name: "Charles "})); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment