1

I am using Handlebars in combination with express.js and registered a custom helper:

let hbs = exphbs.create({
    extname: 'hbs',
    defaultLayout: 'layout',
    layoutsDir: path.join(__dirname, 'views/'),
    partialsDir: [
        path.join(__dirname, 'views/modals/'),
        path.join(__dirname, 'views/partials/'),
        path.join(__dirname, 'views/charts/'),
        path.join(__dirname, 'views/customScripts/'),
    ],
    helpers: {
        when: function(operand_1, operator, operand_2, options){
            // Use with:
            // {{#when <operand1> 'eq' <operand2>}}
            console.log("Using the when helper:");
            console.log("operand_1: " + operand_1 + " operator: " + operator + " operand_2: " + operand_2);
            let operators = {
                'eq': function (l, r) {
                    return l == r;
                },
                'noteq': function (l, r) {
                    return l != r;
                },
                'gt': function (l, r) {
                    return Number(l) > Number(r);
                },
                'or': function (l, r) {
                    return l || r;
                },
                'and': function (l, r) {
                    return l && r;
                },
                '%': function (l, r) {
                    return (l % r) === 0;
                }
            }
            , result = operators[operator](operand_1, operand_2);

            if(result) return options.fn(this);
            else  return options.inverse(this);
        }
    }

In my file I have the following HTML code:

<div class="col-lg-2">
    <label for="assetSelection">
          Asset:
     </label>
    {{currentFormSelectionAsset}} <-- This works
     <select class="form-control" id="assetSelection" name="assetSelection">
        {{#each assetList}}
          <option value="{{this.id}}" {{#when currentFormSelectionAsset 'eq' this.id}}selected{{/when}}>{{this.name}}</option>
        {{/each}}
     </select>
</div>

Calling my html file I only get the following output in my console:

Using the when:
operand_1: undefined operator: eq operand_2: 2

It looks like I cannot pass the variable into my custom helper but due to the fact that I can print it (one line above the select) makes sure that the variable is present and works.

Is there a limitation about using variables inside custom helper or am I missing something?

Fabian
  • 541
  • 9
  • 30
  • Does this answer your question? [Access a variable outside the scope of a Handlebars.js each loop](https://stackoverflow.com/questions/13645084/access-a-variable-outside-the-scope-of-a-handlebars-js-each-loop) – 76484 Jan 03 '22 at 04:17

0 Answers0