andyinabox


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