问题
According to the readme of pug-html-loader, the loader accepts a data
object which is being passed as part of the options
to the template. While not available on the options
within the pug API reference, a grunt plugin I've found (grunt-contrib-pug) uses the API the same way.
I've specified the following options for the loader:
loader: 'pug-html-loader',
options: {
pretty: true,
exports: false,
debug: !env.production,
compileDebug: !env.production,
cache: config.build.useCaching,
doctype: 'html',
data: {
title: config.metadata.title,
baseUrl: config.build.baseUrl,
server: env.server,
metadata: config.metadata
}
}
Which I'd like to access the following way, according to this question:
title= data.title
However, I always run into the following error when compiling:
ERROR in Error: Child compilation failed:
Module build failed: TypeError: Cannot read property 'title' of undefined
For debugging purposes, I've included the following line in the template:
-
console.log(' DATA! ' + data);
Which results in:
DATA! undefined
I've also ensured that the data is correctly being passed to pug by declaring some gibberish instead of an object (e.g. a string, plain json, a number..), then the pug compiler complains that the data is not in valid format etc.
Anyone facing the same issue?
回答1:
You should reference data directy (i.e. without prefixing the fields with data
)
So you should change your code like so:
{
loader: 'pug-html-loader',
options: {
data: {
title: 'Hello World'
}
}
}
And then reference it from your PUG template
doctype html
html
head
title= hello
来源:https://stackoverflow.com/questions/44279144/pass-data-to-pug-using-pug-html-loader-cannot-read-property-of-undefined