Search code examples
node.jsjsonpug

Using Node.js to render data in pug - no data on rendered page


I'm trying to use res.render() to pass data to a Pug template. When I get to this point in my code:

const _renderPage = function(req, res, responseBody) {  
console.log(responseBody);
res.render('page-template', {  
    pageData: responseBody,
    pageTitle: 'this is the about page!' }
    ); 
};

console.log(responseBody) shows:

[  { _id: '5bda4cfc11922d1dc5961922',
    name: 'about',
    body: 'about ksdjflskjflksdfks' }  ]

However, my Pug template which looks like the following, will not print the actual values of pageData.name or pageData.body even though it does print the pageTitle variable:

h1= pageTitle
p Welcome to #{pageData.name}

.row
  .col-12
    p #{pageData.body}

Solution

  • Your root issue is that responseBody is an array, and you are trying to access it as an object.

    Change the render function to feed the first element in the array to the template and it will work as expected:

    res.render('page-template', {  
      pageData: responseBody[0],
      pageTitle: 'this is the about page!' }
    );