1

我正在尝试创建一个以逗号分隔的班级教师名字列表。

所以首先我创建了一个计算属性,如:

App.Class = DS.Model.extend({
    title: DS.attr('string'),
    description: DS.attr('string'),
    start_date: DS.attr('date'),
    end_date: DS.attr('string'),
    teachers: DS.hasMany('App.Teacher'),
    department: DS.attr('string'),

    teacher_list: Ember.computed(function() {
        var teachers = this.get('teachers');
        var teachers_list = '';
        teachers.forEach(function (teacher) {
            teachers_list += teacher.get('first_name');
            if (teachers.indexOf(teacher) < teachers.get('length') - 1) teachers_list += ', ';
        });
        return teachers_list;
    }).property('teachers.@each.first_name')
});

在模板中,它看起来像这样:

...
<td>{{class.teacher_list}}</td>
...

但是后来我想到了将 first_names 链接到教师自己的页面,而我在这里卡住了。我试过下面的代码,但没有运气。

应用程序.js

Ember.Handlebars.registerBoundHelper('teachers_list', function(teachers) {
    var teachers_list = '';
    teachers.forEach(function (teacher) {
        teachers_list += "{{#linkTo 'teacher' " + teacher.id + "}}{{teacher.first_name}}{{/linkTo}}";
        if (teachers.indexOf(teacher) < teachers.get('length') - 1) teachers_list += ', ';
    });
    return (teachers_list);
});

模板

...
<td>{{teachers_list class.teachers}}</td>
...

输出

{{#linkTo 'teacher' 0}}{{teacher.first_name}}{{/linkTo}}, {{#linkTo 'teacher' 1}}{{teacher.first_name}}{{/linkTo}}, {{#linkTo 'teacher' 2}}{{teacher.first_name}}{{/linkTo}}

有没有我从助手内部可以创建正确的链接?

干杯

解决方案

模板:

<td id="teacher-list">{{#each teacher in course.teachers}}<span>{{#linkTo 'teacher' teacher}}{{teacher.first_name}}{{/linkTo}}</span>{{/each}}</td>

CSS:

#teacher-list span:not(:last-of-type)::after { content: ", "; }
4

1 回答 1

1

我宁愿在模板中使用简单的{{#each teachers}}...{{/each}}. 或者,如果您坚持使用 Handlebars 助手,您可以这样做:http ://www.thesoftwaresimpleton.com/blog/2013/04/07/handlebars-helper/

调用linkTo辅助函数可能会很棘手,所以作为中间立场,我建议构建一个视图:

App.TeachersListView = Ember.View.extend({
  teachers: null,
  template: Ember.Handlebars.compile(
    '{{#each teacher in view.teachers}}' +
      '{{#linkTo "teachers" teacher}}{{teacher.name}}{{/linkTo}}' +
    '{{/each}}'
  )
});

然后像这样使用它:

{{view App.TeachersListView teachersBinding="teachersList"}}

但是你不应该在模型中这样做,因为它不属于那里。另外,我会避免将任何内容命名为class/ Class,因为它是几乎所有语言中的保留字,您可能会遇到意外错误。

这是您问题的答案,还是您需要帮助者的进一步帮助linkTo

于 2013-04-09T20:11:00.947 回答