eleventy icon indicating copy to clipboard operation
eleventy copied to clipboard

Added custom Ejs functions support

Open christianzoppi opened this issue 4 years ago • 3 comments

Hi 😄 This PR adds support for custom Ejs functions (also async functions). Example of the syntax is:

module.exports = function(eleventyConfig) {
  eleventyConfig.addEjsFunction("myAsyncFunction", async function(a, b) { … });
};

Users can also use the ejs library to use the render and the compile methods using the ejsEngine (the ejs library object) and ejsOptions (the object of ejs options created by eleventy) passed to the context along with the other data.

// Custom Function Using 
eleventyConfig.addEjsFunction("exampleFunction", function(blocks) {
    return this.ejsEngine.render(`<%- include('/blocks/anothertemplate', {somevar: 'somevarvalue'}) %>`, this, this.ejsOptions);
});

I've added the addEjsFunction call to the methods addShortcode, addFilter, etc.

christianzoppi avatar May 28 '20 06:05 christianzoppi

@zachleat This seems to make sense and is inline with the other template shortcodes\functions. @christianzoppi to get this merged you will want to remove the .DS_Store files and add a test 👍

MadeByMike avatar Jun 22 '20 23:06 MadeByMike

@MadeByMike Thank you. I removed the .DS_Store files and I added 2 tests, for both sync and async functions.

I also removed the async option I initially set for EJS options inside the compile method of the EJS engine, so the user will be able to eventually enable the async feature in EJS by using the ejsOptions object which was already in the config and I didn't notice before.

If you think I need further updates on this please let me know. Thanks for your help, I appreciate it.

christianzoppi avatar Jun 23 '20 12:06 christianzoppi

Sorry guys, I just realised that I didn't mention how options are passed to the function, but I guess you already got it because that's the same way you'd do for JavaScript functions. If you create this function

eleventyConfig.addEjsFunction("outputHeading", function(string) {
    return `<h1>${string}</h1>`;
});

You'd call it like this <%- outputHeading('Hello') %>

christianzoppi avatar Jun 30 '20 06:06 christianzoppi