IT박스

Handlebars.js를 사용하여 기본 "for"루프 반복

itboxs 2020. 10. 23. 07:42
반응형

Handlebars.js를 사용하여 기본 "for"루프 반복


Handlebars.js를 처음 사용했고 방금 사용하기 시작했습니다. 대부분의 예제는 객체에 대한 반복을 기반으로합니다. 기본 for 루프에서 핸들 바를 사용하는 방법을 알고 싶었습니다.

예.

for(i=0 ; i<100 ; i++) {
   create li's with i as the value
}

이것이 어떻게 달성 될 수 있습니까?


이에 대한 핸들 바에는 아무것도 없지만 자신 만의 도우미를 쉽게 추가 할 수 있습니다.

무언가를 n몇 번하고 싶다면 :

Handlebars.registerHelper('times', function(n, block) {
    var accum = '';
    for(var i = 0; i < n; ++i)
        accum += block.fn(i);
    return accum;
});

{{#times 10}}
    <span>{{this}}</span>
{{/times}}

전체 for(;;)루프 를 원하면 다음과 같습니다.

Handlebars.registerHelper('for', function(from, to, incr, block) {
    var accum = '';
    for(var i = from; i < to; i += incr)
        accum += block.fn(i);
    return accum;
});

{{#for 0 10 2}}
    <span>{{this}}</span>
{{/for}}

데모 : http://jsfiddle.net/ambiguous/WNbrL/


다음을 사용할 수 있지만 마지막 / 처음 / 색인을 사용하려는 경우 여기에 최고의 대답이 좋습니다.

Handlebars.registerHelper('times', function(n, block) {
    var accum = '';
    for(var i = 0; i < n; ++i) {
        block.data.index = i;
        block.data.first = i === 0;
        block.data.last = i === (n - 1);
        accum += block.fn(this);
    }
    return accum;
});

{{#times 10}}
    <span> {{@first}} {{@index}} {{@last}}</span>
{{/times}}

CoffeeScript를 좋아한다면

Handlebars.registerHelper "times", (n, block) ->
  (block.fn(i) for i in [0...n]).join("")

{{#times 10}}
  <span>{{this}}</span>
{{/times}}

This snippet will take care of else block in case n comes as dynamic value, and provide @index optional context variable, it will keep the outer context of the execution as well.

/*
* Repeat given markup with given times
* provides @index for the repeated iteraction
*/
Handlebars.registerHelper("repeat", function (times, opts) {
    var out = "";
    var i;
    var data = {};

    if ( times ) {
        for ( i = 0; i < times; i += 1 ) {
            data.index = i;
            out += opts.fn(this, {
                data: data
            });
        }
    } else {

        out = opts.inverse(this);
    }

    return out;
});

참고URL : https://stackoverflow.com/questions/11924452/iterating-over-basic-for-loop-using-handlebars-js

반응형