Skip to content

CodeCoupler Webpack Import EJS Templates

If you need to write a EJS template you can set the end of the name of the HTML file *.ejs.html or *.template.html.

Files ending with *.ejs.html will be parsed by the package ejs. Files ending with *.template.html will be parsed by the underscore function template.

Then you can use variables like <%= locals["some-var"] %> in your template. All HTML templates will be included in the final JavaScript bundle

In your JavaScript file you require them and submit the properties of the variable data like this:

import htmlTemplate from "./path/to/your/file.ejs.html";
let resultingHtml = htmlTemplate({ "some-var": "some-value" });

Linked Assets

To link assets like images you must use the following syntax:

<img src="<%- require('./image.png') %>" />

The filename must start with ./.

Nested Templates

To use the include methods of EJS you have to pay attention to this:

If you are using the ejs parser you cannot use the include() function. You have to use the include preprocessing statement:

<%- include inc/part.html %>

If you are using the template() function you have to include the content from variables like described here: Including nested templates:

index.js:

1
2
3
var mainTemplate = require("ejs!./main.ejs");
var hyperlinkTemplate = require("ejs!./hyperlink.ejs");
var renderedHtml = mainTemplate({ hyperlink: hyperlinkTemplate });

main.ejs:

<h1><%= hyperlink({ name: 'Example', url: 'http://example.com' }) %></h1>

hyperlink.ejs:

<a href="<%= url %>"><%= name %></a>

As a result, renderedHtml becomes a string <h1><a href="http://example.com">Example</a></h1>.