Skip to main content

External data for all templates

Option: data

Type: object | string

Default: {}

Defines template data accessible across all templates.

Configuration

  • object: Object-based data.
  • string: Specifies the path to the template data file.

Key Behaviors:

  • Global scope: Data is available in all templates.
  • Merge Logic: Template-specific data overrides matching properties in the global data object.
  • HMR Support: Webpack detects changes when data is configured as a reference to a data file.
tip

Use the entry data to pass template specifically variables.

object Object-Based Data

Type: object

Directly defines data as a JavaScript object.

Limitations:

  • HMR Support: Requires Webpack restart to reflect changes.

Example

info

The example uses the default Eta template engine. For details, see the preprocessor option.

Webpack config (webpack.config.js):

module.exports = {
plugins: [
new HtmlBundlerWebpackPlugin({
entry: {
index: './src/templates/home.eta',
about: './src/templates/about.eta',
},
data: {
company: {
name: 'Awesome Corp',
address: '123 Main Street, Springfield',
phone: '+1 234 567 890',
email: 'info@awesomecorp.com',
},
},
}),
],
};

Templates:

<!DOCTYPE html>
<html lang="en">
<head>
<title>Home</title>
</head>
<body>
<h1>Welcome to <%= company.name %></h1>

<% /* pass data to the partial with `it` */ %>
<%~ include('src/templates/partials/footer.html', it) %>
</body>
</html>

Shared footer (src/templates/partials/footer.eta):

<footer>
<p>&copy; <%= company.name %> - All rights reserved</p>
<p>Address: <%= company.address %></p>
<p>Phone: <%= company.phone %></p>
<p>Email: <%= company.email %></p>
</footer>

string File Reference Data

Type: string

Specifies an absolute or relative path to a JSON or JavaScript file. For a JavaScript file, the module must export an object.

Supported formats:

  • JavaScript
  • JSON

HMR Support:

  • Changes initiate Webpack recompilation if the file is part of the watch configuration.

Example

Webpack config (webpack.config.js):

module.exports = {
plugins: [
new HtmlBundlerWebpackPlugin({
entry: {
index: './src/templates/home.eta',
about: './src/templates/about.eta',
},
data: './src/data/company.json',
}),
],
};

Template data file (JSON and JavaScript format):

{
"company": {
"name": "Awesome Corp",
"address": "123 Main Street, Springfield",
"phone": "+1 234 567 890",
"email": "info@awesomecorp.com"
}
}

See template examples by Object-Based Data.

Use Case Comparison

dataBest ForHMR Support
objectStatic dataNo
stringDynamic/editable dataYes

Notes

Relative paths are resolved using Webpack the context configuration.

References: