我正在尝试创建一个逗号分隔的班级教师名字列表。
首先,我创建了一个计算属性,如:
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链接到教师自己的页面的想法,在这里我被卡住了。 我尝试过以下代码,但没有运气。
App.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: ", "; }
答案 0 :(得分: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
助手的进一步帮助?