dc7290 / template-ejs-loader

ejs-loader with webpack5 support. Chain it to html-loader and use it with html-webpack-plugin.
MIT License
24 stars 3 forks source link

Data as a function #21

Closed Eutrepe closed 2 years ago

Eutrepe commented 2 years ago

Hi, thx for this plugin

I have a problem. How can I use data as a function in .ejs

Something like this: <%= foo('something') %>

I try by:

 template: htmlWebpackPluginTemplateCustomizer({

  templatePath:'./src/pages/indexPage/index.ejs',
  templateEjsLoaderOption:{ 
    data: { 
      foo: (text) => text + '_test',
    }
  }
}),

and/or in "simple" htmlWebpackPlugin

templateParameters: {
  foo: (text) => text + '_test',
},

but I always get foo is not defined

dc7290 commented 2 years ago

@Eutrepe

Thank you for using this library.

Regarding the main issue, that you cannot specify function as data. This library does not currently support function.

This is because there is no way to access the html-webpack-plugin data from within the loader, and the Instead, the webapck loader inline is used to send data to the ejs file in a pseudo fashion.

In the future, we would like to be able to specify templateParameters of html-webpack-plugin, but We have not been able to support this due to lack of time. If we could add this feature, it would solve @Eutrepe's problem.

mizok commented 2 years ago

@Eutrepe I am actually not sure what kind of function you are going to inject as data, but maybe you can try THIS instead ?

index.ejs: (assume you have your ejs file at root level)

<% const methods = require('./src/js/methods.js') %>
<%= methods.foo('123')  %>

methods.js:

module.exports = {
   foo:(text)=>text
}
mizok commented 2 years ago

@Eutrepe

Actually there is a way if you REALLY need to inject individual function into several ejs files. You can try parse all your function into String , and call them using eval in ejs file

like this:

index.ejs:

<%= eval(foo)('123')%>

webpack.config.js:

template: htmlWebpackPluginTemplateCustomizer({

  templatePath:'./src/pages/indexPage/index.ejs',
  templateEjsLoaderOption:{ 
    data: { 
      foo: "(text) => text + '_test' ", // the output will be 123_test
    }
  }
}),

BUT this is kinda dirty honestly :/

Eutrepe commented 2 years ago

@dc7290 @mizok thx <3