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

1

2

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?

Nobukonoby answered 31/5, 2017 at 8:10 Comment(0)
C
5

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 Updated

doctype html
html
  head
    title= title
Chartier answered 7/6, 2017 at 20:53 Comment(1)
Don't you mean title=title or data: { hello: 'Hello World' }Bandler

© 2022 - 2024 — McMap. All rights reserved.