Reputation: 13
I've got some node js code which is responsible for creating a function, that I want to execute in my .pug template.
let pages = [
{
"id": 0,
"name": "Index"
},
{
"id": 1,
"name": "About"
},
{
"id": 2,
"name": "Kontakt"
},
];
function navigation(pages) {
return pages;
}
app.get("/", (req, res) => {
res.write(navigation(pages));
res.render("index");
});
How can I call for this function in the pug template or what is a better way to pass a function from node to jade?
Upvotes: 1
Views: 2057
Reputation: 73
OK ffmaer between that answer and your demo you almost got me to where I needed to be... Now the problem is that i need to pass a variable to the script.
When I use the following code i get
Uncaught ReferenceError: p is not defined
doctype html
html
head
title foobar
script !{getProfile}
body
ul
each p in profiles
script.getProfile(p);
but if do
doctype html
html
head
title foobar
script !{getProfile}
body
ul
each p in profiles
li=p
everything works perfectly.
Upvotes: 0
Reputation: 781
Assuming you are using express.js with node.js,
in the node.js back end, write:
function navigation() {
let pages = [
{
id: 0,
name: "Index"
},
{
id: 1,
name: "About"
},
{
id: 2,
name: "Kontakt"
}
];
return pages;
}
app.get("/", (req, res) => {
res.render("index", { navigation: navigation });
});
In the pug template, write:
script !{navigation}
A demo: https://glitch.com/edit/#!/pass-javascript-functions-from-node-js-to-pug
Upvotes: 2