Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass variable from jade-loader to a jade template file?

Tags:

I want to pass my data-object to jade files, but but it is impossible My jade-loader:

{
   test: /\.jade$/,
   loader: "jade",
   query: {
      pretty: true,
      locals: {
          name: "Georg"
    }
}

}

plugins:

plugins: [
    new HtmlWebpackPlugin({
       filename: "index.html",
       template: "./src/jade/index.jade"
})]

index.jade:

span=locals.name

I run webpack and I get this index.html:

<span></span>

My variable name don't pass. Why? How to fix it?

like image 589
leshiple Avatar asked Jun 10 '16 19:06

leshiple


People also ask

How do you add variables to a pug?

tag, all that's needed to set up a variable in Pug is a hyphen. If you then just want to put that variable into the DOM as-is, an equals sign can accomplish that. Though the example below isn't practical, it helps to show how variables can be set and used in their simplest form.

What is Jade templating?

Jade is a template engine for node. js and the default rendering engine for the Express web framework. It is a new, simplified language that compiles into HTML and is extremely useful for web developers. Jade is designed primarily for server-side templating in node.


1 Answers

You can pass the custom properties to HtmlWebpackPlugin options and use them in your pug templates (see htmlWebpackPlugin.options in documentation). It works with the latest versions of the HtmlWebpackPlugin, pug-loader and webpack 2. Can't confirm that it works with the previous versions, but I believe it does.

pug rule:

{
  test: /\.pug$/,
  loader: 'pug-loader',
  options: {
    // Use `self` namespace to hold the locals
    // Not really necessary
    self: true,
  },
}

HtmlWebpackPlugin options:

{
  filename: 'index.html',
  template: 'src/html/index.pug',

  // Your custom variables:
  name: 'Georg',
}

Using it in index.pug template:

span= self.htmlWebpackPlugin.options.name

Note that you can set the self option to false and omit it in your pug templates using variables directly. For more details see the Pug reference.

like image 117
edloidas Avatar answered Sep 28 '22 02:09

edloidas