eleventy icon indicating copy to clipboard operation
eleventy copied to clipboard

Handling custom tag in excerpt output

Open MiloCasagrande opened this issue 5 years ago • 2 comments

Hi,

I have a custom nunjucks tag registered in my .eleventy.js file:

 config.addNunjucksTag('ref', function () {});

that I use to retrieve the URL of the passed argument (the file name) in my .md files:

[another post]({% ref 'another-post.md' %})

This works fine when rendering the whole content, but it does not work within an excerpt snippet.

In this example:

---
title: Foo
---

Link to [another post]({% ref 'another-post.md' %})
<!--more-->

When I render the excerpt in this way:

{{ post.data.page.excerpt | markdown | safe }}

What I get out is something like this:

Link to [another post]({% ref <a href="/another-post.md">another-post.md</a> %})

The href attribute does not have the correct URL, and the rendering is not correct. I know I'm missing a step there to pass the exercpt through the nunjucks engine, but even with a custom filter that doesn't seem to work.

Is it possible to correctly render the excerpt snippet? Is there a way to access the engine from inside a filter to correctly use the template engine where the custom tag has been registered?

MiloCasagrande avatar May 22 '20 10:05 MiloCasagrande

I ran into the same issue - the excerpt is not passed through the markdownTemplateEngine. Until this is fixed, I have to resort to an eval Nunjucks tag to parse the excerpt as template, but it is pretty ugly.

vseventer avatar Jun 06 '20 00:06 vseventer

I resorted to use another hack.

I created an excerpt filter that takes the whole content of the page, and then from inside the filter I use my custom instance of nunjucks passing it the correct context. Something like this:

config.addFilter('excerpt', function (content) {
  return nunjucksLib.renderString(content.data.page.excerpt, {
    collections: content.data.collections,
  });
});

This then needs to be passed through a markdown filter, depending on the need.

MiloCasagrande avatar Jun 07 '20 13:06 MiloCasagrande