Home > Enterprise >  Get options sent to pug with space in the name
Get options sent to pug with space in the name

Time:06-16

I am trying to send JSON options into a pug file with a space in the attribute names.

For example, inside an express get request:

let json = {"Attribute Name With Spaces": "Value"}
res.render('loader.pug', json);

How do I access this data in the pug file? It is difficult to change the format of the json because it is external and not something I made myself.

CodePudding user response:

Pug makes locals available under the locals property so you can simply use the following...

h1= locals["Attribute Name With Spaces"]
p Here's the var #{locals["Attribute Name With Spaces"]}

I couldn't find any official documentation for this so it might not always be a reliable option.


Another option to make this easier would be to simply bundle all your json properties under a single object...

res.render("loader.pug", { props: json });

Then you can use something like this

h1= props["Attribute Name With Spaces"]
p #{props["Attribute Name With Spaces"]}

Alternately, transform your object to normalise the keys

res.render(
  "loader.pug",
  Object.fromEntries(
    Object.entries(json).map(([key, val]) => [key.replaceAll(" ", "_"), val])
  )
);

and use

h1= Attribute_Name_With_Spaces
  • Related