Skip to content

Commit

Permalink
Adds setAsync Nunjucks shortcode. set isn’t async friendly. Resto…
Browse files Browse the repository at this point in the history
…res `this.ctx` in Nunjucks shortcodes. Fixes #2108. Fixes #1584. Fixes #1596.
  • Loading branch information
zachleat committed Nov 20, 2021
1 parent f3831c3 commit eca0925
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/Engines/Nunjucks.js
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,12 @@ class Nunjucks extends TemplateEngine {
this.addFilters(this.config.nunjucksAsyncFilters, true);

// TODO these all go to the same place (addTag), add warnings for overwrites
// TODO(zachleat): variableName should work with quotes or without quotes (same as {% set %})
this.addPairedShortcode("setAsync", function (content, variableName) {
this.ctx[variableName] = content;
return "";
});

this.addCustomTags(this.config.nunjucksTags);
this.addAllShortcodes(this.config.nunjucksShortcodes);
this.addAllPairedShortcodes(this.config.nunjucksPairedShortcodes);
Expand Down Expand Up @@ -211,6 +217,7 @@ class Nunjucks extends TemplateEngine {
static _normalizeShortcodeContext(context) {
let obj = {};
if (context.ctx && context.ctx.page) {
obj.ctx = context.ctx;
obj.page = context.ctx.page;
}
return obj;
Expand Down
1 change: 1 addition & 0 deletions src/Plugins/RenderPlugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,7 @@ function EleventyPlugin(eleventyConfig, options = {}) {

let normalizedContext = {};
if (context.ctx && context.ctx.page) {
normalizedContext.ctx = context.ctx;
normalizedContext.page = context.ctx.page;
}

Expand Down
9 changes: 9 additions & 0 deletions test/TemplateRenderPluginTest.js
Original file line number Diff line number Diff line change
Expand Up @@ -200,3 +200,12 @@ test("Capture nunjucks render output to a liquid variable", async (t) => {
);
t.is(html, `4`);
});

// Idea from https://twitter.com/raymondcamden/status/1460961620247650312
// Possibly blocked by async in {% set %} https://github.com/mozilla/nunjucks/issues/815
test("Capture liquid render output to a njk variable", async (t) => {
let html = await getTestOutputForFile(
"./test/stubs-render-plugin/capture-liquid.njk"
);
t.is(html, `4`);
});
11 changes: 11 additions & 0 deletions test/stubs-render-plugin/capture-liquid.njk
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
argData:
num: 2
---
{% setAsync "liquidOutput" %}
{% renderTemplate "liquid", argData %}
{% assign liquidVar = num | times: 2 %}
{{ liquidVar }}
{% endrenderTemplate %}
{% endsetAsync %}
{{ liquidOutput }}

0 comments on commit eca0925

Please sign in to comment.