0

Handlebarjsを使用して、配列をループし、区切り文字で区切って値を表示したいと思います。表示したいコンテンツもテンプレートでなければ簡単です;)

これが私の場合です:

accounts = [
     {'name': 'John', 'email': 'john@example.com'},
     {'name': 'Malcolm', 'email': 'malcolm@example.com'},
     {'name': 'David', 'email': 'david@example.com'}
];

{{#each accounts}}
    <a href="mailto:{{ email }}" title="Send an email to {{ name }}">{{ name }}</a>,
{{/each}}

この実装の問題は、次の出力が得られることです。

ジョン、マルコム、デビッド、

そして、私はそれをしたいです:

ジョン、マルコム、デビッド

どうやってやるの ?

4

2 に答える 2

3

CSS疑似クラス:afterをコンテンツと一緒に使用して、必要な「フォーマット」を実現できます。(:afterそして今日のほとんどのブラウザとIE8 +でのコンテンツサポート。)

例えば:

HTML:

<a href="mailto:xxx@xxxx.com" title="Send an email to Foo">Foo1</a>
<a href="mailto:xxx@xxxx.com" title="Send an email to Foo">Foo2</a>
<a href="mailto:xxx@xxxx.com" title="Send an email to Foo">Foo3</a>

CSS:

a {
  color: red;
}
a:after {
  content: ", ";
}
a:last-child:after {
  content: "";
}

結果:

Foo1, Foo2, Foo3
于 2012-12-13T15:00:14.407 に答える
2

トリックを実行できる新しいforeachヘルパーを実装しました:

Handlebars.registerHelper('foreach', function (array, fn) {
    var total = array.length;
    var buffer = '';

    //Better performance: http://jsperf.com/for-vs-foreach/2
    for (var i = 0, j = total; i < j; i++) {
        var item = array[i];

        // stick an index property onto the item, starting with 1, may make configurable later
        item['_index'] = i+1;
        item['_total'] = total;
        item['_isFirst'] = (i === 0);
        item['_isLast'] = (i === (total - 1));

        // show the inside of the block
        buffer += fn.fn(item);
    }

    // return the finished buffer
    return buffer;
});

その後 :

{{#foreach accounts}}
    <a href="mailto:{{ email }}" title="Send an email to {{ name }}">{{ name }}</a>{{#unless _isLast}}, {{/unless}}
{{/foreach}}
于 2012-12-13T13:41:31.403 に答える