Search code examples
handlebars.js

handlebar comparison operator inside each loop


I have two type of value on handlebar page and needs to compare the first one from second. I can print value of following code

{{articledetails.content_writer_id}}

before writing each loop on page. Now i want to compare the value like following. but i can not get the scope of articledetails.content_writer_id in below code.

{{#each contentwriterdetails}}       
{{#compare this.id "==" articledetails.content_writer_id }}

I have already registered compare helper by using this code.

 handlebars.registerHelper('compare', function (lvalue, operator, rvalue, options) {
var operators, result;
if (arguments.length < 3) {
    throw new Error("Handlerbars Helper 'compare' needs 2 parameters");
}

if (options === undefined) {
    options = rvalue;
    rvalue = operator;
    operator = "===";
}

operators = {
    '==': function (l, r) { return l == r; },
    '===': function (l, r) { return l === r; },
    '!=': function (l, r) { return l != r; },
    '!==': function (l, r) { return l !== r; },
    '<': function (l, r) { return l < r; },
    '>': function (l, r) { return l > r; },
    '<=': function (l, r) { return l <= r; },
    '>=': function (l, r) { return l >= r; },
    'typeof': function (l, r) { return typeof l == r; }
};

if (!operators[operator]) {
    throw new Error("Handlerbars Helper 'compare' doesn't know the operator " + operator);
}

result = operators[operator](lvalue, rvalue);

if (result) {

    return options.fn(this);
} else {

    return options.inverse(this);
}

 });

and above helper is working fine as i have checked that.

Any help would be appreciated.


Solution

  • Use the parent's context path:

    {{#each contentwriterdetails}}       
    {{#compare this.id "==" ../articledetails.content_writer_id }}