Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

displaying values from sequelize query using handlebars

I have a Cart model with product_price and quantity. I am writing a sequelize query to calculate the total as price * quantity Here's my query

db.Cart.findAll({

    attributes: {include: [[db.sequelize.condition(db.sequelize.col('cart_quantity'), '*', db.sequelize.col('price')),'tot']]}

})

Sequelize documentatoin says to access the value of 'tot' we use instance.get('tot'). So in the results console.log(item.get('tot') displays correct value

.then(function(dbCart) { //We have access to the products as an argument inside of the callback function

  dbCart.forEach(function(item){
    console.log(item.get('tot'));
  });
  var hbsObject = {
    products: dbCart,
  };
res.render("shop/cart", hbsObject);
});

});

Now when I try to access the value in my carts.handlebars file I am unable to display or access the value of 'tot' {{# each products }} {{tot}} or {{Cart.tot}} or {{products.tot}} or {{products.get('tot')}} yields no value {{/each}} How do I access and display the value of 'tot' in handlebars? Thank you

like image 567
Priya Balakrishnan Avatar asked Jul 18 '26 18:07

Priya Balakrishnan


2 Answers

Try:

{{#each users}}
    {{#dataValues}}
        <p>Username: {{username}}</p>
        <p>Email: {{email}}</p>
    {{/dataValues}}
{{/each}}

Or try:

{{#each users}}
    <p>Username: {{this.dataValues.username}}</p>
    <p>Email: {{this.dataValues.email}}</p>
{{/each}}
like image 198
Denis Francia Karell Avatar answered Jul 21 '26 09:07

Denis Francia Karell


As far as I can tell you can only access the result of the query with item.get('tot'), but since you can't call functions from handlebars you need a work around. One way to do it is to add a handlebars helper that just wraps the .get() function.

const Handlebars = require('handlebars');
Handlebars.registerHelper('sequelizeGet', function(obj, col) {
  return obj.get(col);
}); 

And in the handlebars template access that helper like:

<span>{{sequelizeGet item 'tot'}}</span>
like image 21
C.J. Windisch Avatar answered Jul 21 '26 09:07

C.J. Windisch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!