简体   繁体   中英

Passing an object to an ejs loader, using html-webpack-plugin

I believe I've looked everywhere, but I've come up empty handed. I've been using html-webpack-plugin to load a single index.html file from my source, but my client has come with some localisations, and I thought it would be great if I could add them dynamically.

So I'm trying to switch over to using a templating engine with html-webpack-plugin , namely ejs , but I'm having major problems!

I want html-webpack-plugin to render and .ejs file, and I need to give said .ejs file a huge object of localisations.

I want something like this:

<h1><%= header.title %></h1>

Coming from a localisation .json -file like this:

{
  "header": {
    "title": "My Clients Super Awesome Website"
  }
}

I've tried using two different ejs webpack loaders, and I simply can't figure out how to pass a simple object to the ejs loader, that I can use in my ejs file.

Hope you guys have some answers :D Thanks in advance.

in index.ejs

<%= htmlWebpackPlugin.options.header.title %>

in webpack.config.js

module: {
    rules: [
    {
        test: /.ejs$/,
        loader: 'ejs-loader'
    }
]}

and

plugins: [
new HtmlWebpackPlugin({
    header: {title: 'test'},
    template: './index.ejs',
})]

Notice. do not use options: { variable: 'data or xxx' } after ejs-loader , if variable is specified, htmlWebpackPlugin will be unknown.

So you need use html-webpack-plugin in your webpack configuration. And put the object into HtmlWebpackPlugin's parameter.

I was looking for the same thing. Seems like the template can access options object passed to html-webpack-plugin as htmlWebpackPlugin.options object.

To include eg. the title, you need to reference it from the template as htmlWebpackPlugin.options.title . I don't know if there any way to pass values in more plugin-agnostic way, so you can just reference title as title in the template file.

easy insert any paramaters.

// webpack.config.js

    ...
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: 'template/index.ejs',
      templateParameters: {
        'title': 'My Clients Super Awesome Website',
        'episode: '2'
      }
    }),
    ...
<!-- index.ejs -->

<%= title %>
<%= episode %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM