Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make nunjucks env available to shortcodes in addition to filters #3175

Open
andyinabox opened this issue Jan 25, 2024 · 2 comments
Open

Make nunjucks env available to shortcodes in addition to filters #3175

andyinabox opened this issue Jan 25, 2024 · 2 comments

Comments

@andyinabox
Copy link

andyinabox commented Jan 25, 2024

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

@edwardhorsford
Copy link
Contributor

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.

@andyinabox
Copy link
Author

@edwardhorsford thanks! I'm pretty new here, hadn't thought of that...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants