如何在HtmlWebpackPlugin和twig-loader中使用变量?

时间:2017-06-08 09:30:40

标签: javascript json webpack twig html-webpack-plugin

我制作了一个小型引擎来创建一个多语言模板。 使用从twig到HTML的HtmlWebpackPlugin,从json文件加载一些动态变量。 但是在编译之后我仍然在HTML文件中看到我的变量......

有人知道我可以在哪些地方做些改进吗? 或者我做错了什么?

Webpack.config.js:

'use strict';
var path = require('path');
var _ = require('lodash');
var webpack = require('webpack');
var timestamp = require('time-stamp');
var packageJson = require('./package.json');
var autoprefixer = require('autoprefixer');
var htmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var pages = require('./templates.json');

var templatePages = _.map(pages, function(page) {
let translation = require('./src/assets/translations/lang.'+page.lang+'.json');
return new htmlWebpackPlugin({ 
    filename: page.filename, 
    template: page.template,
    trans: translation
 });
});

const DEV_DIR = './src';
const DIST_DIR = './dist';

module.exports = {
    devtool: "source-map",
    entry: {
        app: [DEV_DIR+'/js/app.js',DEV_DIR+'/css/main.scss']
    },
    output: {
        path: path.resolve(__dirname, 'tmp'),
        filename: "[name].js",
        library: "[name]"
    },
resolve: {
    extensions: ['', '.js', '.twig']
},
module: {
    preLoaders: [{
        test: /\.js$/,
        exclude: /(bin|node_modules|bower_components|grunt|gulp|bower)/,
        loaders: ['eslint-loader']
    }],
    loaders: [{
        test: /\.js$/,
        exclude: /(bin|node_modules|bower_components|grunt|gulp|bower)/,
        loader: 'babel',
        query: {
            presets: ['es2015'],
            babelrc: false
        }
    }, {
        test: /\.scss$/,
        loader: ExtractTextPlugin.extract(
            'style-loader',
            'css-loader!postcss-loader!sass-loader'
        )
    }, {
        test: /\.(jpe?g|png|gif|svg|ico)$/i,
        loaders : [
            'file-loader?hash=sha512&digest=hex&name=/assets/img/[name].[ext]',
        ]
    },{
        test: /\.(json)$/i,
        loaders : [
            'file-loader?hash=sha512&digest=hex&name=/assets/translations/[name].[ext]',
        ]
    }, {
        test: /\.twig$/,
        loader: "twig-loader"
    }]
},
devServer : {
    contentBase : 'tmp',
    inline      : true
},
eslint: {
    configFile: './.eslintrc'
},
sasslint: {
    configFile: './sass-lint.yml',
    emitError: true
},
plugins: [
    new ExtractTextPlugin(
        '/css/main.css',
        { allChunks: true }
    ),
    new webpack.DefinePlugin({
        __DEBUG     : JSON.stringify(true),
        __NAME      : JSON.stringify(packageJson.name),
        __DESC      : JSON.stringify(packageJson.description),
        __VERSION   : JSON.stringify(packageJson.version),
        __TIMESTAMP : JSON.stringify(timestamp('YYYY/MM/DD HH:mm:ss:ms'))
    }),
    new webpack.optimize.UglifyJsPlugin({
        compress: {
            warnings: false
        },
        output: {
            comments: false
        }
    }),
    new webpack.ProvidePlugin({
        Logger   : path.resolve(__dirname, 'libs/Logger')
    })
].concat(templatePages),
};

模板Json:

[
    {
        "filename": "./nl/index.html",
        "template": "./src/twig/index.twig",
        "lang": "nl"
    },
    {
        "filename": "./fr/index.html",
        "template": "./src/twig/index.twig",
        "lang": "fr"
    },
    {
        "filename": "./de/index.html",
        "template": "./src/twig/index.twig",
        "lang": "de"
    }
]

翻译文件:

{"toggle_mobile":"Menu",
"menu_primary_introduction":"Introductie",
"menu_primary_reference":"Referenties",
"menu_primary_information":"Aanpak",
"menu_primary_contact":"Contact",}

Index.twig:

<!DOCTYPE html>
<html lang="<%= htmlWebpackPlugin.options.trans.menu_lang_short %>">
<head>
    <meta charset="utf-8" />
    <meta name="keywords" content="" />
    <meta name="description" content="Title CMS" />
    <meta name="author" content="Company BVBA" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Title CMS</title>
    <link type="image/x-icon" href="/assets/img/favicon.ico" rel="shortcut icon" />
    <script src="https://use.typekit.net/oww0qak.js"></script>
    <script>try{Typekit.load({ async: true });}catch(e){}</script>
    <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500" rel="stylesheet">
</head>
<body>
    <div class="page-body">

        <header class="header-primary">
            <%= htmlWebpackPlugin.options.trans.menu_primary_introduction %>
        </header>
    </div>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

固定!

我对JS / HTML <%= =%>和twig的方法感到困惑。 对于树枝,没有必要使用<%= =%>。我必须只使用{{ }}

所以我的工作成果,例如:

<span class="navbar-toggler-text">{{ htmlWebpackPlugin.options.trans.toggle_mobile }}</span>