我正在尝试创建一个以逗号分隔的班级教师名字列表。
所以首先我创建了一个计算属性,如:
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: ", "; }