Eleventy: Using shortcodes within other shortcodes?

Created on 18 Apr 2020  路  4Comments  路  Source: 11ty/eleventy

I have several universal shortcodes that are defined in their own .js files, which I import and register in my .eleventy.js file. In my case, I have 2 shortcodes:

config.addShortcode('excerpt', excerptShortcode);
config.addShortcode('docs', docsShortcode);

I am trying to use the excerpt shortcode inside the docs shortcode (by doing this.excerpt()) but it doesn't seem to be defined... is this expected, or is it a bug?

Both shortcodes do work as expected within regular pages or templates.

Eleventy v0.10.0 btw 馃榿

education

Most helpful comment

You're welcome, @chasemccoy!

PS, To be clear, you _can_ bind this to arrow functions on array methods鈥攂ut you must pass this as thisArg.

All 4 comments

@zachleat If this is expected behavior, I would be happy to file a feature request! I think it would be valuable to compose shortcodes upward, which would require the ability to use shortcodes in shortcodes.

@chasemccoy,

I use shortcodes and filters inside others often, so I鈥檓 not sure about any bug.

Do you have example code to share?

By chance are you trying to use Array.prototype.map(), .filter(), .reduce() or some similar method? (Just an educated guess since you mentioned an undefined function error.) In that case, by default, your this in this.excerpt() would be assigned to the global object inside the callback for those methods. So, you鈥檇 have to set this with the optional thisArg (MDN docs) in such methods. For example:

// Example file ./_includes/shortcodes/docs.js
module.exports = eleventyConfig =>
  eleventyConfig.addShortcode('docs', function (arrayDataForDocs) {
    arrayDataForDocs.map(function (currentItemInDocsArray) {
      return `${this.excerpt(currentItemInDocsArray)}`
    }, this) // <-- optional `thisArg` to maintain the value of `this`
  })

Or, are you using an arrow function in your this.docs() when you call your this.excerpt()? In that case, this is not bound at all (see warning in 11ty docs), and you鈥檇 want to use traditional function syntax.

Does any of that help?

@reubenlillie That was exactly the problem! I knew about the restrictions with arrow functions, but I did _not_ know about thisArg! I'm kinda surprised I've never had a use for that before now.

Anyway, thank you very much for the help! I wonder if this should be called out in the docs? I know it's not an Eleventy thing, but it seems like this would be a common stumbling block for people. I'd be happy to open a PR to update docs to mention this if so.

@reubenlillie I appreciate the assist! Now if we can just get #1052 fixed I will be set.

You're welcome, @chasemccoy!

PS, To be clear, you _can_ bind this to arrow functions on array methods鈥攂ut you must pass this as thisArg.

Was this page helpful?
0 / 5 - 0 ratings