eleventy
eleventy copied to clipboard
Make nunjucks `env` available to shortcodes in addition to filters
Is your feature request related to a problem? Please describe.
I'm interested in accessing the nunjucks environment to create shortcodes that do custom rendering. One examples is a shortcode that includes a template with a specific context (similar to the Twig include "template.html" with data
behavior):
{% includeWith "template.njk", data %}
Another possible application is creating shortcodes that render a nunjucks template to generate output. So, for instance, for an image
shortcode you could write the markup as a nunjucks template and import/render that.
Describe the solution you'd like
I'd like to be able to access the nunjucks environment from the this
object in shortcode functions, as is already the case with filters. This would allow me to do something like:
eleventyConfig.addNunjucksShortcode('includeWith', function (template, ctx) {
return this.env.filters.safe(this.env.render(template, ctx))
})
Which would allow
{% includeWith "template.njk", data %}
Describe alternatives you've considered
This is possible to do as a filter, but I think it makes more sense as a shortcode:
eleventyConfig.addNunjucksFilter('includeWith', function (template, ctx) {
return this.env.filters.safe(this.env.render(template, ctx))
})
But this to me seems kind of awkward and hacky.
{{ "template.njk" | includeWith({ data: data }) }}
Additional context
No response
I can't directly help but another alternative might be a nunjucks global?
The syntax would then be:
{{ includeWith("template.njk", { data: data }) }}
This might be closer to what you're looking for, and has a nice benefit of using {{
rather than {%
which feels more 'correct' to me for some thing that's going to render to the page vs an expression.
@edwardhorsford thanks! I'm pretty new here, hadn't thought of that...
Fixed by #3355, which adds this.env
to Nunjucks shortcode function contexts. Test added for future compat.
Shipped with https://github.com/11ty/eleventy/releases/tag/v3.0.0-alpha.15