farling42/obsidian-import-json

add math helper?

rokville opened this issue · 4 comments

Feature Request:

Could you add the "math" helper?

This StackOverflow seemed to have the same idea as I was thinking
https://stackoverflow.com/questions/22103989/adding-offset-to-index-when-looping-through-items-in-handlebars

relevant post:
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}}

Would the existing math support in the handlebars-helpers package not suffice?

Your example can be done with:

 {{#each myArray}} <span>{{add @index 1}}</span> {{/each}}

See the "math" section of the readme of the package https://github.com/Budibase/handlebars-helpers

(The above link is already provided in my readme.)

More complex math is done with embedded function calls:

{{ add 10 (multiply @index 5) }}

Amazing, thank you. I am completely new to handlebars, and I appreciate your direct help. Your plugin has been a lifesaver for a novice trying to back up some old info.