1

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?

1
  • @xMayank yes, kind of Commented Jul 5, 2020 at 10:01

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

I strongly suspect you're confusing client and server-side scripting here. Where are these profiles coming from? What exactly do you expect getProfile to do?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.