Pass data to pug using pug-html-loader (cannot read property of undefined)

天大地大妈咪最大 提交于 2019-12-31 03:19:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!