farling42 / obsidian-import-json

Plug-in for Obsidian.md which will create Notes from JSON files
MIT License
85 stars 5 forks source link

add math helper? #27

Closed rokville closed 1 year ago

rokville commented 1 year ago

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}}
farling42 commented 1 year ago

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}}
farling42 commented 1 year ago

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.)

farling42 commented 1 year ago

More complex math is done with embedded function calls:

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

rokville commented 1 year ago

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.