Escape keyword in the handlebar template

血红的双手。 提交于 2019-12-23 23:12:39

问题


I have a collection of objects (MyApp.instrsController, an ArrayController) and each object has a property called 'action' (a float number), how can I display it using the handlebars template?

Below is the code I've tried:

<ul>
{{#each MyApp.instrsController}}
   <li>{{action}}</li>
{{/each}}
</ul>

But since 'action' is a 'keyword', it throws javascript runtime error 'options is undefined'.

Thanks in advanced.


回答1:


You can manually specify that you're looking for a property in the current context by preceding the property name with this.:

{{this.action}}



回答2:


If you can't change the property name you can use a computed property in your model object, see http://jsfiddle.net/pangratz666/4ZQM8/:

Handlebars:

<script type="text/x-handlebars" >
    <ul>
        {{#each App.controller}}
            <li>{{actionProp}}</li>
        {{/each}}
    </ul>
</script>

JavaScript:

App.Object = Ember.Object.extend({
    actionProp: function() {
        return this.get('action');
    }.property('action')
});


App.controller = Ember.ArrayController.create({
    content: [],

    addObj: function(number) {
        this.pushObject(App.Object.create({
            action: number
        }));
    }
});

If you don't have a custom model object, you can use a computed property on a CollectionView, see http://jsfiddle.net/pangratz666/r6XAc/:

Handlebars:

<script type="text/x-handlebars" data-template-name="item" >
    {{actionProp}}
</script>​

JavaScript:

Ember.CollectionView.create({
    contentBinding: 'App.controller',
    itemViewClass: Ember.View.extend({
        templateName: 'item',
        actionProp: function(){
            return this.getPath('content.action');
        }.property()
    })
}).append();



回答3:


I seriously suggest that you just change the name of the property. You are spending time working on a problem that is not core to your domain.

YAGNI. KISS.

The biggest lesson to learn in programming is how to get things made and done rather than how to manipulate javascript into not throwing a snit over your use of a reserved keyword. You will be happier later if you don't have a fragile solution that looks tricky to understanc

Since this is a float, can I suggest you use "actionLevel"?




回答4:


just use model.property,such as:

{{input class="input-xlarge" value=model.content }}


来源:https://stackoverflow.com/questions/10809185/escape-keyword-in-the-handlebar-template

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