mirta
mirta

Reputation: 678

Webpack: include html partial inside another partial?

Is there a way to include html partial inside another partial using webpack? I am using html-loader to do this:

index.html

<%= require('html-loader!./partials/_header.html') %>

But when I try to include another partial inside a _header.html it is not able to render it.

This is not working:

_header.html

<%= require('html-loader!./partials/_nav.html') %>

Upvotes: 5

Views: 4141

Answers (2)

JanuszO
JanuszO

Reputation: 1240

I was combining a little and I was able to find a solution.

index.html

<%= require('html-loader?root=.&minimize=true&interpolate!./partials/_header.html') %>

and then in _header.html

${require('html-loader?root=.!../partials/_nav.html')}

Upvotes: 4

pldg
pldg

Reputation: 2588

Using html-loader with interpolate option.

https://github.com/webpack-contrib/html-loader#interpolation

{ test: /\.(html)$/,
  include: path.join(__dirname, 'src/views'),
  use: {
    loader: 'html-loader',
    options: {
      interpolate: true
    }
  }
}

And then in html pages you can import partials html and javascript variables.

<!-- Importing top <head> section -->
${require('./partials/top.html')}
<title>Home</title>
</head>
<body>
  <!-- Importing navbar -->
  ${require('./partials/nav.html')}
  <!-- Importing variable from javascript file -->
  <h1>${require('../js/html-variables.js').hello}</h1>
  <!-- Importing footer -->
  ${require('./partials/footer.html')}
</body>
</html>

html-variables.js looks like this:

const hello = 'Hello!';
const bye = 'Bye!';

export {hello, bye}

You can also include partials inside another partial the same way, using ${require('path/to/your/partial.html').

The only downside is that you can't import other variables from HtmlWebpackPlugin like this <%= htmlWebpackPlugin.options.title %> (at least I can't find a way to import them), just write the title in your html or use a separate javascript file for handle variables if needed.

Upvotes: 0

Related Questions