Search code examples
javascripthtmlnode.jsexpress-handlebars

Can't print element of array in handlebars template


I'm trying to print a list of products to one of my handlebar views and it won't let me print a specific property of one of the objects inside array I passed in.

store.js:

This is what I used to render the handlebars view:

res.render("products.handlebars", { products });

I logged "products" right before it got passed to the line above, it's an array of objects

and in the products.handlebars file:

this prints the entire array and all of the contents of the object inside the products.handlebars view

{{#each products}}
{{this}}
{{/each}}

but if I want to print a property of any of the objects like so:

{{#each products}}
{{this.title}}
{{/each}}

nothing shows up, literally nothing. no errors, no 'undefined' just nothing.

I'm pretty sure I'm getting the syntax inside {{this.title}} wrong but I'm not sure. I used this exact code in another project and it worked fine. I don't know what I am doing wrong here.

And for reference I console logged the array I passed in right before my res.render and it looked fine. Here's what the elements of the array look like(this is just the 1st element):

{
title: 'Samsung Galaxy S20 Ultra 1TB',
price: 1999.99,
description: 'Lorem ipsum dolor...',
quantity: 10,
category: 'Mobile',
bestSeller: false,
imgPath: '/public/images/products/galaxys20ultra.png',
}

Solution

  • I figured it out. A recent update of express-handlebars disabled access of properties from objects by default. You need to re-enable it in your app.engine function.

    https://handlebarsjs.com/api-reference/runtime-options.html#options-to-control-prototype-access