Skip to content

Instantly share code, notes, and snippets.

@cowboyd
Last active September 12, 2022 20:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cowboyd/832989c6021c2fe06f86a0e4432ac558 to your computer and use it in GitHub Desktop.
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.
// 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