1
votes

I'm trying to create a comma separated list of teacher first names of a class.

So firstly I created a computed property like:

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('[email protected]_name')
});

And in the template it looks something like this:

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

But then I got the idea to make the first_names links to the teachers own page and here I'm stuck. I've tried the following code but without luck.

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);
});

Template

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

Output

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

Is there somehow I from inside the helper can create the correct link?

Cheers

Solution

Template:

<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: ", "; }
1

1 Answers

1
votes

I'd rather do this in the template with a simple {{#each teachers}}...{{/each}}. Or, if you insist on doing it with a Handlebars helper, here is how you can do it: http://www.thesoftwaresimpleton.com/blog/2013/04/07/handlebars-helper/

Calling the linkTo helper function can be tricky, so as a middle ground I suggest building a view:

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

And then use it like this:

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

But you should NEVER do this in the model, as it does no belong there. Also, I'd avoid naming anything to class/Class, as it's a reserved word in almost all languages, and you might run into unexpected errors.

Is this an answer to your question, or you need further help with the linkTo helper?