Answer the question
In order to leave comments, you need to log in
How to set up Twig in Webpack?
Hello, I am building a project on webpack, I connected twig-loader and twig-html-loader to it.
The build configuration is the following:
const path = require('path');
const HTMLWebpackPlugin = require('html-webpack-plugin');
const {CleanWebpackPlugin} = require('clean-webpack-plugin');
const resolvePath = place => {
return path.resolve(__dirname, place);
};
module.exports = {
context: resolvePath('app'),
entry: resolvePath('main.js'),
output: {
filename: './js/bundle.[hash].js',
path: resolvePath('public')
},
plugins: [
new HTMLWebpackPlugin({
title: 'WebPack',
template: './twig/index.twig'
}),
new CleanWebpackPlugin()
],
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
},
{
test:/\.twig$/,
use: [
'raw-loader',
{
loader: 'twig-html-loader',
options: {
data: {
page: {
title: 'page title'
},
title: 'hello'
},
namespaces: {
layouts: path.resolve(__dirname, './app/twig/templates'),
components: path.resolve(__dirname, './app/twig/components')
}
}
}
]
}
]
}
};
<body>
<header>
Шапка
</header>
<main>
<p>
<a href="/index.html">Главная</a>
</p>
</main>
<footer>
Подвал
</footer>
<script type="text/javascript" src="./js/bundle.30e46863c97b9f1fb740.js"></script></body>
<body>
<header>
Шапка
</header>
<main>
<p>
<a href="/index.html">Главная</a>
</p>
</main>
<footer>
Подвал
</footer>
<script type="text/javascript" src="./js/bundle.30e46863c97b9f1fb740.js"></script>
</body>
{% extends "layouts::_template.twig" %}
{% block content %}
<p>
<a href="/index.html">Главная</a>
</p>
{% endblock %}
_template.twig:
<code lang="html">
{% block html %}
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>{{ page.title }}</title>
</head>
<body>
{% block body %}
<header>
Шапка
</header>
<main>
{{ block('content') }}
</main>
<footer>
Подвал
</footer>
{% endblock %}
</body>
</html>
{% endblock %}
</code>
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question