0

I can't figure out how to access JSON data in my pug templates.

Here is my pug layout

title #{htmlWebpackPlugin.pages[page].title}

Pug page which is initializing page variable

block vars
 - var page = "catalog"

Webpack part

new HtmlWebpackPlugin({
    filename: 'catalog.html',
    chunks: ['main'],
    template: PATHS.source + '/views/pages/catalog.pug',
    inject: true,
    data: {
        pages: require('./dev/util/options.json')
    }
})

JSON

"pages": {
    "catalog": {
        "title": "Catalog",
        "description": "",
        "keywords": ""
    }
}
Graham
  • 7,431
  • 18
  • 59
  • 84
cygnus
  • 149
  • 3
  • 11

1 Answers1

0

Each page is a separate pug and json. First, I declare the entry, in my case it is a separate js file entry.js

module.exports.html = {
     'index': 'index',
     'about': 'o-mnie',
     'contact': 'kontakt'
};

Webpack part

Include entry:

const entry = require('./entry.js');

Next add entry to HtmlWebpackPlugin:

const entryHtmlPlugins = Object.keys(entry.html).map(entryName => {
    return new HtmlWebpackPlugin({
        filename: `${entry.html[entryName]}.html`,
        template: `./source/templates/containers/${entryName}/${entryName}.pug`,
        chunks: [entryName],
        file: require(`../source/templates/containers/${entryName}/${entryName}.json`)
    })
});

See the full code how to use json data from pug and webpack -> github

const webpack = require("webpack");
const path = require('path');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const HtmlWebpackPlugin = require('html-webpack-plugin');
const SimpleProgressWebpackPlugin = require('simple-progress-webpack-plugin');

const entry = require('./entry.js');

const entryHtmlPlugins = Object.keys(entry.html).map(entryName => {
    return new HtmlWebpackPlugin({
        filename: `${entry.html[entryName]}.html`,
        template: `./source/templates/containers/${entryName}/${entryName}.pug`,
        path: path.join(__dirname, "../dist/"),
        chunks: [entryName],
        // inject: true,
        // cache: true,
        file: require(`../source/templates/containers/${entryName}/${entryName}.json`),
        mode: 'development'
    })
});

const output = {
    path: path.resolve(__dirname, "source"),
    filename: "[name].[hash].js",
    publicPath: "/"
}

const config = {
    devtool: "eval-source-map",
    mode: "development",
    entry: entry.site,
    output: output,
    module: {
        rules: [
            {
                // JS
                test: /\.js$/,
                exclude: /node_modules/,
                use: {
                    loader: "babel-loader",
                }
            },
            {
                // CSS | SCSS
                test: /\.(css|scss)$/,
                use: ExtractTextPlugin.extract({
                    fallback: 'style-loader',
                    use: [{
                            loader: 'css-loader'
                        },
                        {
                            loader: 'postcss-loader',
                            options: {
                                plugins: () => [require('autoprefixer')({
                                    'browsers': ['> 1%', 'last 2 versions']
                                })],
                            }
                        },
                        {
                            loader: 'sass-loader'
                        },
                        {
                            loader: 'sass-resources-loader', // style-resources-loader then we can use sass, less, stylus
                            options: {
                                resources: [
                                    path.resolve(__dirname, '../source/scss/main.scss')
                                ]
                            },
                        }
                    ]
                })
            },
            {
                // IMAGES
                test: /\.(jpe?g|png|gif|svg)$/i,
                loader: "file-loader"
            },
            {
                // PUG
                test: /\.pug$/,
                loader: 'pug-loader',
                options: {
                    pretty: true,
                    self: true
                }
            }
        ],
    },
    plugins: [
        new SimpleProgressWebpackPlugin({
            format: 'compact'
        }),
        new ExtractTextPlugin({
            filename: '[name].[hash].css',
            // disable: false,
            allChunks: true
        }),
        new webpack.DefinePlugin({
            PRODUCTION: JSON.stringify(false)
        }),
    ].concat(entryHtmlPlugins)
};

module.exports = config;
Grzegorz T.
  • 3,903
  • 2
  • 11
  • 24
  • 1
    While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/low-quality-posts/20978423) – Rahul Sep 27 '18 at 13:35
  • 1
    Thank you, I will try to improve this entry. This is my first answer on this page ;) – Grzegorz T. Sep 27 '18 at 13:59