IT TIP

마지막 요소 뒤를 제외하고 {{#each}} 루프의 요소 사이에 구분 기호를 추가하려면 어떻게해야합니까?

itqueen 2020. 12. 31. 23:14
반응형

마지막 요소 뒤를 제외하고 {{#each}} 루프의 요소 사이에 구분 기호를 추가하려면 어떻게해야합니까?


배열에서 쉼표로 구분 된 항목 목록을 생성하려는 Handlebars 템플릿이 있습니다.

내 Handlebars 템플릿에서 :

{{#each list}}
    {{name}} {{status}},
{{/each}}

내가 원하는 ,마지막 항목에 표시되지 수 있습니다. 핸들 바에서이 작업을 수행하는 방법이 있습니까? 아니면 CSS 선택기로 돌아 가야합니까?

업데이트 : Christopher의 제안에 따라 이것이 내가 구현 한 것입니다.

var attachments = Ember.CollectionView.extend({
    content: [],
    itemViewClass: Ember.View.extend({
        templateName: 'attachments',
        tagName: 'span',
        isLastItem: function() {
            return this.getPath('parentView.content.lastObject') == this.get('content');
        }.property('parentView.content.lastObject').cacheable()
    })
}));

그리고 내 관점에서 :

{{collection attachments}}

및 항목보기 :

{{content.title}} ({{content.size}}) {{#unless isLastItem}}, {{/unless}}

이를 위해 표준 CSS를 사용할 수 있습니다.

li:after {
    content: ',';
}

li:last-of-type:after {
    content: '';
}

나는 별도의 규칙을 선호하지만 (주석의 @Jay에서) 약간 덜 읽기 쉬운 버전이면 더 간결합니다.

li:not(:last-of-type):after {
    content: ',';
}

부품에 늦었지만 WAYYYY보다 간단한 방법을 찾았습니다.

{{#unless @last}},{{/unless}}

Ember v1.11부터는 블록 매개 변수를 사용하여 각각의 인덱스를 얻을 수 있습니다. 귀하의 경우 이것은 다음과 같습니다.

{{#each list as |item index|}}
    {{if index ", "}}{{item.name}} {{item.status}}
{{/each}}

첫 번째 index값은 0평가되고 false추가되지 않을 것이며, 모든 후속 값이 평가되어 true구분 기호가 앞에 추가됩니다.


나는 이것이 1 년이라는 것을 알고 있지만 비슷한 문제가 있었고 여기에 상처를 입었습니다. 제 경우에는 실제로 배열을 다루었습니다. 그래서 여기 내 해결책이 있습니다.

Handlebars.registerHelper('csv', function(items, options) {
    return options.fn(items.join(', '));
});

// then your template would be
{{#csv list}}{{this}}{{/csv}}

템플릿에 csv 로직을 유지하는 간단하고 우아한 솔루션을 찾고있었습니다.


sep 블록 도우미를 만들었습니다.

Handlebars.registerHelper("sep", function(options){
    if(options.data.last) {
        return options.inverse();
    } else {
        return options.fn();
    }
});

용법:

{{#each Data}}
   {{Text}}{{#sep}},{{/sep}}
{{/each}}

else 문을 지원합니다.


ember 2.7에서는 다음을 설치 한 후이를 수행 할 수 있습니다 ember-truth-helpers.

ember install ember-truth-helpers

템플릿은 다음과 같습니다.

{{#each model as |e|}}
    {{e}}{{#unless (eq e model.lastObject)}}, {{/unless}}
{{/each}}

나는 freak3dot의 답변의 수정 된 버전으로 작업했습니다.

handlebars.registerHelper('csv', function(items, options) {
  return items.map(function(item) {
    return options.fn(item)
  }).join(', ')
})

(이것은 노드 앱이므로 map그에 따라 밑줄 또는 브라우저에서 빌드하는 경우 변경하십시오 )

Allows for formatting objects between each comma:

{{#csv players}
  {{firstName}} {{lastName}}
{{/csv}}

Edit: Here's a more flexible version. Join a list of things on an arbitrary separator.

handlebars.registerHelper('join', function(items, separator, options) {
  return items.map(function(item) {
    return options.fn(item)
  }).join(separator)
})

And template:

{{#join players ' vs '}
  {{firstName}} {{lastName}}
{{/join}}

Maybe for this context, you should be creating a view for the collection, not an iteration of views on the member items. In this case, a Handlebar iterator is overkill. In my example below, changes to the firstName or lastName on the Person objects will be bound to the list and update the view.

Template:

{{App.listController.csv}}

Javascript:

App = Ember.Application.create();

var Person = Ember.Object.extend({
    firstName: null,
    lastName: null
});

var bob = Person.create({
    firstName: "bob",
    lastName: "smith"
});

var ann = Person.create({
    firstName: "ann",
    lastName: "doe"
});

App.listController = Ember.Object.create({
    list: [bob, ann],
    csv: Ember.computed(function () {
        var arr = [];
        this.get('list').forEach(function (item, index, self) {
            arr.push(item.firstName + ' ' + item.lastName);
        })
        return arr.join(',');
        }).property('list.@each.firstName', 'list.@each.lastName')
});
// any changes to bob or ann will update the view
bob.set('firstName', 'tim');
// adding or removing from the array will update the view
App.listController.get('list').pushObject(Person.create(firstName: "Jack", lastName:"Dunn"});

Below is my original answer, that didn't work for this context.

You should be able to do this with a helper:

Handlebars.registerHelper('csv', function(items, options) {
  var out = "";
  for(var i=0, l=items.length; i<l; i++) {
    out += options.fn(items[i]);
    if (i < l - 1) {
        out += ',';
    }
    // might want to add a newline char or something
  } 
  return out;
});

// then your template would be
{{#csv list}} {{name}} {{status}} {{/each}}

ReferenceURL : https://stackoverflow.com/questions/10403003/how-do-i-add-a-separator-between-elements-in-an-each-loop-except-after-the

반응형