11ty / eleventy

A simpler site generator. Transforms a directory of templates (of varying types) into HTML.
https://www.11ty.dev/
MIT License
17.29k stars 496 forks source link

Add content to a nunjucks block from shortcodes #561

Closed bert-bruggeman closed 5 years ago

bert-bruggeman commented 5 years ago

How can I add content to a block in a layout from shortcodes? I would also like to use variables or objects like "collections" in schortcodes, is this possible?

eleventy.js

  let nunjucks = new Nunjucks.Environment(
    new Nunjucks.FileSystemLoader("includes")
  );
  eleventyConfig.setLibrary("njk", nunjucks)

  eleventyConfig.addShortcode("button", (arg = {}) => {
    arg.target = (arg.href.lastIndexOf("http", 0) === 0) ? "_blank" : ""
    return nunjucks.render('components/button.njk', arg)
  })
components/button.njk
<a href="{{ href }}"{% if target %} target="{{ target }}"{% endif %}{% if id %} id="{{ id }}"{% endif %} class="btn{% if class %} {{ class }}{% endif %}">{{ text }}</a>
{% block js %}
... can't add content to js block in layouts/page.njk
{% endblock %
kleinfreund commented 5 years ago

Elventy calls "shortcodes for blocks" paired shortcodes. There is documentation for this feature, too: https://www.11ty.io/docs/shortcodes/#paired-shortcodes.

bert-bruggeman commented 5 years ago

Thanks for the anwser, but thats not what i mean,... An example: I would like to add a script or additional items to the footer of a page from a shortcode in the content, nunjucks uses "block" to accomplish this but I can't seem to find a way to make this work...

veleek commented 5 years ago

You've given an example of how you're defining you shortcode but it might be helpful to provide a sample input and expected output so we can see exactly what you're trying to accomplish.

Are you saying that you want a eleventy shortcode to be able to return Nunjucks content which will then be processed by Nunjucks? I'm not sure if there's an EASY way to accomplish this because it could potentially result problems when the Nunjucks code you're producing ends up calling itself it a loop.

bert-bruggeman commented 5 years ago

I now realize using nunjucks blocks is not the correct way to solve my problem,... See issue 566, maybe this is a better method to achieve my goal...