mercredi 27 janvier 2016

How do I translate #if type handlebars helpers from ember 1.7 to ember-cli (2.3)

I have this registered handlebars helper in ember1.7 right now.

var get = Ember.Handlebars.get;
Ember.Handlebars.registerHelper('ifCond', function(val1, val2, options) {
    var context = (options.fn.contexts && options.fn.contexts[0]) || this;
    var val1 = get(context, val1, options.fn);
    if (val1 == val2) {
        return options.fn(this);
    } else {
        return options.inverse(this);
    }
});

The idea is pretty simple: take first parameter as a context property, second parameter as an actual value, and return a boolean based on their equality. So, for example, if I have a property age on an object user,

{{#ifCond user.age "22" }}
  <h2> Twin Twos!</h2>
{{/ifCond}}

would be a snippet I would use to render the h2 element when the condition is fulfilled.

However, I cannot figure out how to translate such a helper for ember-cli.

I've considered making a component, but I need a conditional, not something that renders a specific set of DOM elements. I feel like I'm missing something. How would I be able to make {{#ifCond}} work in Ember 2.3?

EDIT: I found a helper creation doc that let me to this implementation:

import Ember from 'ember';

export function ifCond(params/*, hash*/) {
    return (params[0] === params[1]);
  // return params;
}

export default Ember.Helper.helper(ifCond);

however, for this to work, I would have to write (in the template)

{{#if (ifCond 1 1)}}
  yep
{{/if}}

Is there still a way to actually use the handlebar helper as we could in ember 1.7 ?




Aucun commentaire:

Enregistrer un commentaire