Is it possible to pass conditionals or other javascript as arguments in ember handlebars?

只愿长相守 提交于 2019-12-17 22:28:33

问题


I would like to pass a true/false statement to my handlebars

{{Gd-text-input label="Specify" name="Specify" key="entry.810220554" hideIf="entry.18110 === "Client""}}

I would like hideIf to be true if the variable entry.18110 is set to "Client


回答1:


First, add this somewhere -

Handlebars.registerHelper('ifEqual', function (var1, var2, options) {
    if (var1=== var2) {
        return new Handlebars.SafeString(options.fn(this));
    }
    return new Handlebars.SafeString(options.inverse(this));
});

Then..

{{#ifEqual entry.18110 "Client"}}
{{Gd-text-input label="Specify" name="Specify" key="entry.810220554" hideIf="true"}}
{{else}}
{{Gd-text-input label="Specify" name="Specify" key="entry.810220554" hideIf="false"}}
{{/if}}

This is pretty much the only way to do it, as the handlebars team has specifically left most logic out of the templates since it generally doesn't belong there. Which is debatable, as sometimes it makes things more complicated not to allow simple logic. But, this is very workaroundable.




回答2:


The other answer does not work for Ember Handlebars, for your case you could do something like this.

http://emberjs.jsbin.com/agewuxAT/3/edit

Component

App.HideableCompComponent = Em.Component.extend({
  isHidden: function(){
    var prop = this.get('hideIfProperty');
    if(!prop) return false;
    // allow lazy comparison? up to you
    return this.get('content').get(prop) == this.get('hideIfValue');
  }.property('hideIfProperty', 'hideIfValue')
});

Template

<script type="text/x-handlebars" data-template-name="components/hideable-comp">
  {{#unless isHidden}}
    I am a component I am not hidden!
  {{else}}
    I am hidden
  {{/unless}}
</script>

Usage

{{hideable-comp content=model hideIfProperty='length' hideIfValue=3}}


来源:https://stackoverflow.com/questions/20330130/is-it-possible-to-pass-conditionals-or-other-javascript-as-arguments-in-ember-ha

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!