johnknoop / vscode-handlebars-preview

Preview Handlebars templates in VS Code
MIT License
16 stars 10 forks source link

Boolean type helpers #40

Closed utillity closed 3 years ago

utillity commented 3 years ago

I'm trying to emulate the helpers provided by SendGrid, but the preview just renders TRUE or FALSE, instead of interpreting the helper as a condition.

Helper:

module.exports = {
    equals: function (text, compare) {
            var v1 = text?.toLowerCase() ?? "";
            var v2 = compare?.toLowerCase() ?? ""
            return v1 == v2;
    },
    greaterThan: function (v1, v2) {
        return Number(v1) > Number(v2);
    }
};

Usage:

{{#greaterThan scoreOne scoreTwo}}
    Congratulations, you have the high score today!
{{/greaterThan}}
utillity commented 3 years ago

just found out they are called block-helpers: https://handlebarsjs.com/guide/block-helpers.html#basic-blocks. Is there a way to auto-register these?

utillity commented 3 years ago

ah, never mind. It seems there is the options property added as the last parameter of the function, so I can implement it as in the examples.

here's my working `equals` block helper:

    equals: function(v1, v2, options) {
        // options: { name:string, hash:object, data:{ root:object } }

        v1 = v1?.toLowerCase() ?? "";
        v2 = v2?.toLowerCase() ?? "";

        if (v1 == v2) {
            return options.fn(this);
        } else {
            return options.inverse && options.inverse(this) || "";
        }
    },