TwigJS
Link: TwigJS
You need to install the twig
package:
npm i -D twig
preprocessor: 'twig'
For example, there is the layout template src/views/layout/default.twig
<!DOCTYPE html>
<html>
<head>
<title>{{ title }}</title>
<script src="@scripts/main.js" defer="defer"></script>
</head>
<body>
<h1>{{ headline }}!</h1>
<div id="content">{% block content %}{% content %}</div>
{% include "@partials/footer.twig" %}
</body>
</html>
The page template src/views/pages/home.twig can be extended from the layout:
{% extends '@layouts/default.twig' %}
{% block content %}
<ul id="people">
{% for item in people %}
<li>{{ item }}</li>
{% endfor %}
</ul>
{% endblock %}
Define the preprocessor
as twig
:
const path = require('path');
const HtmlBundlerPlugin = require('html-bundler-webpack-plugin');
module.exports = {
resolve: {
alias: {
'@scripts': path.join(__dirname, 'src/scripts/'),
},
},
plugins: [
new HtmlBundlerPlugin({
entry: {
index: {
import: 'src/views/page/home.twig',
data: {
title: 'Strartpage',
headline: 'Breaking Bad',
people: ['Walter White', 'Jesse Pinkman'],
},
},
},
preprocessor: 'twig', // Use TwigJS templating engine
preprocessorOptions: {
// aliases used for extends/include
namespaces: {
layouts: 'src/views/layout/',
partials: 'src/views/partials/',
},
},
}),
],
};
preprocessorOptions
{
preprocessor: 'twig',
preprocessorOptions: {
async: false,
autoescape: false,
namespaces: {
layouts: 'src/views/layouts',
partials: 'src/views/partials',
},
},
},
The TwigJS have few useful options:
async {boolean}
defaults is'false'
.autoescape {boolean}
defaults is'false'
. Escape dangerous characters.namespaces {Object}
defaults is{}
.
The key is a namespace (like Webpack alias) used in the template instead a relative path.
The value is an absolute a path relative to the project directory.
The used namespace must begin with the leading @
symbol:
{% extends "@layouts/default.twig" %}
{% include "@partials/articles/sidebar.twig" %}
You can use a relative path:
{% extends "../layouts/default.twig" %}
{% include "../partials/articles/sidebar.twig" %}
warningThe dynamic including is not supported.
For example, passingmyTemplate
as a parameter does not work:{# page.twig #}
{% extends myTemplate %}
warningThe Twig template containing
tabs
will not be compiled into HTML.
Use thespaces
as an indent in templates. Thetabs
are not supported byTwigJS
.