3

I'm trying to build a small app to call from a config.js file containing JSON and write that data to a page based on the name key within the JSON.

app.get('/:verb', function(req, res) {

    if(!!req.param.verb) {
       config.data.forEach(function(o) {
           var verbName    = o.name,
               description = o.description;

       });

    };
res.render('verb', {title: verbName, subtitle: description});
});

What I'm trying to do is use the verbName and description javascript variables as Jade variable in the res.render structure. As it stands this code will fail due to verbName and description not being strings.

Is it possible to include variables this way?

PS - been in express 1 week and Jade 2 days, so all ideas/solutions would be appreciated.

2
  • I am not sure I understand your problem. What do you mean by "this code will fail". Do you get an error message ? If that's the case, could you post it please ? It's perfectly possible to pass variable to your Jade views. They will available in Jade in the locals object. So you should be able to access them by doing locals["title"] & locals["subtitle"]. Commented Jul 31, 2014 at 10:52
  • There isn't an error message as such - I receive a 500 from the server and the parts of the page relying on this code fail to appear. I will look into the locals object. Essentially I am trying to use var verbName = o.name to provide data to the title object. I can't get res.render to accept a variable for title. If that is solved using locals then that's excellent. Commented Jul 31, 2014 at 11:01

1 Answer 1

3

You are declaring your variables in the wrong scope. You are also overwriting them on each of the forEach loop executions

app.get('/:verb', function(req, res) {

    var verbName,
        description;

        if(!!req.param.verb) {
           config.data.forEach(function(o) {
               verbName    = o.name,
               description = o.description;

           });

        };
    res.render('verb', {title: verbName, subtitle: description});
    });
Sign up to request clarification or add additional context in comments.

Comments

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.