I'm iterating over a list in Handlebars using the built-in each
helper.
Within the each block, I'm referencing the current loop index {{@index}}
to print the consecutive number of an item:
<script id="list-item-template" type="text/x-handlebars-template">
{{#each items}}
<li class="topcoat-list__item">
<a href="#{{@index}}">Item number {{@index}}</a>
</li>
{{/each}}
</script>
This gives the following output:
The problem is that I want to display an offsetted index which starts with 1 instead of 0.
I tried to perform calculations on the index like {{@index+1}}
, but this just leads to an
Uncaught Error: Parse error
The main layout is the HTML page wrapper which can be reused for the different views of the app. {{{body}}} is used as a placeholder for where the main content should be rendered.
Helpers are the proposed way to add custom logic to templates. You can write any helper and use it in a sub-expression. For example, in checking for initialization of a variable the built-in #if check might not be appropriate as it returns false for empty collections (see Utils.isEmpty).
Handlebars HTML-escapes values returned by a {{expression}}. If you don't want Handlebars to escape a value, use the "triple-stash", {{{. You have to use a triple-stash {{{}}} around your data in order to display what you want.
Handlebars doesn't allow you to write JavaScript directly within templates. Instead, it gives you helpers. These are JavaScript functions that you can call from your templates, and help you reuse code and create complex templates. To call a helper, just use it as an expression - {{helpername}} .
Handlebars gives you the possibility to write a custom helper that handles this situation, e.g. a helper function that lets you perform calculations on expressions like addition and subtraction etc.
Below function registers a new helper, which simply increments a value by 1:
var Handlebars = require('handlebars');
Handlebars.registerHelper("inc", function(value, options)
{
return parseInt(value) + 1;
});
You can then use it within the handlebar expression using the inc
keyword, like:
{{inc @index}}
Actual answer: https://stackoverflow.com/a/46317662/1549191
Register a math handlebar and perform all mathematical operations.
app.engine('handlebars', exphbs({
helpers:{
// Function to do basic mathematical operation in handlebar
math: function(lvalue, operator, rvalue) {lvalue = parseFloat(lvalue);
rvalue = parseFloat(rvalue);
return {
"+": lvalue + rvalue,
"-": lvalue - rvalue,
"*": lvalue * rvalue,
"/": lvalue / rvalue,
"%": lvalue % rvalue
}[operator];
}
}}));
app.set('view engine', 'handlebars');
Then you can directly perform operation in your view.
{{#each myArray}}
<span>{{math @index "+" 1}}</span>
{{/each}}
I believe you can use...
{{math @index "+" 1}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With