Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
155
rated 0 times [  158] [ 3]  / answers: 1 / hits: 19341  / 8 Years ago, wed, december 21, 2016, 12:00:00

I'm practicing node, and I ran to a little problem. I'm using handlebars as a templating engine, and mongoose for interaction with my database. In my .hbs template I am looping through each record from the database, and of course I passed the records to my view with



router.get('/', function(req, res, next) {
Exam.find(function(err, predmeti) {
if (err) {
console.log(err);
}
res.render('index',{
predmeti: predmeti
})
})

});


Now when im looping through predmeti with #each, engine throws an error when I try doing math expressions such as



{{#each predmeti}}
<h1>{{100/(brKolokvijuma/finished)}}</h1>
{{/each}}


brKolokvijuma and finished both have a number value, but for some reason I get a error Expecting ID got OPEN_SEXPR



So I'm assuming handlebars won't let me do math expressions when I'm looping through an array. How can I solve this?


More From » node.js

 Answers
14

There are plugins for Handlebars to enable you to do the things they think you shouldn't do in views, but everyone still wants to.



For example the Assemble.io maths helpers and nested expressions would enable you to do something like:



{{#each predmeti}}
<h1>{{divide 100 (divide brKolokvijuma finished)}}</h1>
{{/each}}


A second method, if your maths expressions are not so varied and reused around your views (common calculations e.g. tax or rounding), you could write your own simpler/lighter plugin:



Handlebars.registerHelper(divideMyThings, function(thing1, thing2, thing3) {
return thing1 / thing2 / thing3;
});


Called in your template:



{{divideMyThings 100 brKolokvijuma finished}}


Thirdly you can often precompute data-tables until you only have one variable, and then use the builtin lookup feature. This requires no additional plugins. This is probably not helpful to this specific question, but I thought I'd mention it as a tool.


[#59622] Monday, December 19, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ryleymarkelb

Total Points: 554
Total Questions: 106
Total Answers: 95

Location: Norway
Member since Mon, May 23, 2022
2 Years ago
;