使用 pug-html-loader 将数据传递给 pug(无法读取未定义的 属性)

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

根据 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 的自述文件)以相同的方式使用 API。

我已经为加载程序指定了以下选项:

  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
    }
  }

根据,我想通过以下方式访问:

title= data.title

但是我编译的时候总是运行出现如下错误:

ERROR in   Error: Child compilation failed:
  Module build failed: TypeError: Cannot read property 'title' of undefined

出于调试目的,我在模板中添加了以下行:

-
  console.log(' DATA! ' + data);

这导致:

DATA! undefined

我还通过声明一些乱码而不是对象(例如字符串、普通 json、数字..)来确保数据正确传递给哈巴狗,然后哈巴狗编译器抱怨数据格式无效等

有人面临同样的问题吗?

您应该直接引用数据(即不在字段前加上 data

所以你应该像这样更改你的代码:

{
  loader: 'pug-html-loader',
  options: {
    data: {
      title: 'Hello World'
    }
  }
}

然后从您的 PUG 模板中引用它 已更新

doctype html
html
  head
    title= title