warunkowo ostatnia Pozycja w tablicy przy użyciu kierownicy.szablon js

Używam kierownicy.js dla mojego silnika szablonów i szukam warunkowego wyświetlania segmentu tylko wtedy, gdy jest to ostatnia Pozycja w tablicy zawartej w obiekcie konfiguracyjnym szablonów.

{
  columns: [{<obj>},{<obj>},{<obj>},{<obj>},{<obj>}]
}

Już wyciągnąłem helpera, aby zrobić jakieś porównania / większe/mniejsze-niż i udało mi się zidentyfikować początkowy element w ten sposób, ale nie miałem szczęścia w dostępie do długości mojej tablicy docelowej.

Handlebars.registerHelper('compare', function(lvalue, rvalue, options) {...})

"{{#each_with_index columns}}"+
"<div class='{{#equal index 0}} first{{/equal}}{{#equal index ../columns.length()}} last{{/equal}}'>"+
"</div>"+
"{{/each_with_index}}"

Czy ktoś zna Skrót, inny podejście, i kilka dobroci kierownicy, które powstrzymają mnie od rozerwania kierownicy.silnik js do ustalenia najlepszego kursu?

Author: techie.brandon, 2012-07-13

6 answers

Od wersji Handlebars v1. 1. 0, Możesz teraz używać wartości logicznych @first i @last w każdym helperze dla tego problemu:

{{#each foo}}
    <div class='{{#if @first}}first{{/if}}
                {{#if @last}} last{{/if}}'>
      {{@key}} - {{@index}}
    </div>
{{/each}}

Szybkim pomocnikiem, który napisałem jest:

Handlebars.registerHelper("foreach",function(arr,options) {
    if(options.inverse && !arr.length)
        return options.inverse(this);

    return arr.map(function(item,index) {
        item.$index = index;
        item.$first = index === 0;
        item.$last  = index === arr.length-1;
        return options.fn(item);
    }).join('');
});

Wtedy możesz napisać:

{{#foreach foo}}
    <div class='{{#if $first}} first{{/if}}{{#if $last}} last{{/if}}'></div>
{{/foreach}}
 114
Author: Kara Brightwell,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-13 17:47:58

Od wersji 1.1.0, first I last stały się natywne dla każdego pomocnika. Zobacz bilet #483.

Użycie jest jak Klasa pomocnicza:

{{#each foo}}
    <div class='{{#if @first}}first{{/if}}{{#if @last}} last{{/if}}'>{{@key}} - {{@index}}</div>
{{/each}}
 159
Author: Jacob van Lingen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 11:46:52

Jeśli spróbujesz obsłużyć pierwszy element tablicy, może to pomóc

{{#each data-source}}{{#if @index}},{{/if}}"{{this}}"{{/each}}

@ index jest dostarczany przez każdy helper i dla pierwszej pozycji będzie równy zeru i dlatego może być obsługiwany przez helper if.

 26
Author: Yong Qu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-02-19 01:58:24

Rozwiązanie:

<div class='{{#compare index 1}} first{{/compare}}{{#compare index total}} last{{/compare}}'></div>

Wykorzystanie pomocników z poniższego bloga i gist...

Https://gist.github.com/2889952

Http://doginthehat.com.au/2012/02/comparison-block-helper-for-handlebars-templates/

// {{#each_with_index records}}
//  <li class="legend_item{{index}}"><span></span>{{Name}}</li>
// {{/each_with_index}}

Handlebars.registerHelper("each_with_index", 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;
    // show the inside of the block
    buffer += fn(item);
  }

  // return the finished buffer
  return buffer;

});

Handlebars.registerHelper('compare', function(lvalue, rvalue, options) {

    if (arguments.length < 3)
        throw new Error("Handlerbars Helper 'compare' needs 2 parameters");

    operator = options.hash.operator || "==";

    var operators = {
        '==':       function(l,r) { return l == r; },
        '===':      function(l,r) { return l === r; },
        '!=':       function(l,r) { return l != r; },
        '<':        function(l,r) { return l < r; },
        '>':        function(l,r) { return l > r; },
        '<=':       function(l,r) { return l <= r; },
        '>=':       function(l,r) { return l >= r; },
        'typeof':   function(l,r) { return typeof l == r; }
    }

    if (!operators[operator])
        throw new Error("Handlerbars Helper 'compare' doesn't know the operator "+operator);

    var result = operators[operator](lvalue,rvalue);

    if( result ) {
        return options.fn(this);
    } else {
        return options.inverse(this);
    }

});

Zauważ, że indeks początkowy jest prawidłowy 1.

 1
Author: techie.brandon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-25 19:17:34

Zrobiłem kilka ulepszeń w helperze z Matt Brennan , możesz używać tego helpera z obiektami lub tablicami, To rozwiązanie wymaga Underscore biblioteka:

Handlebars.registerHelper("foreach", function(context, options) {
  options = _.clone(options);
  options.data = _.extend({}, options.hash, options.data);

  if (options.inverse && !_.size(context)) {
    return options.inverse(this);
  }

  return _.map(context, function(item, index, list) {
    var intIndex = _.indexOf(_.values(list), item);

    options.data.key = index;
    options.data.index = intIndex;
    options.data.isFirst = intIndex === 0;
    options.data.isLast = intIndex === _.size(list) - 1;

    return options.fn(item, options);
  }).join('');
});

Użycie:

{{#foreach foo}}
    <div class='{{#if @first}}first{{/if}}{{#if @last}} last{{/if}}'>{{@key}} - {{@index}}</div>
{{/foreach}}
 0
Author: ebaranov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:25:58

Tylko dla twojej wiadomości: Jeśli utkniesz z kierownicą

Zdefiniuj właściwość podobną do isLast na obiektach, które iterujesz i używaj jej tak jak

{{#each objectsInList}}"{{property}}": "{{value}}"{{#unless isLast}},{{/unless}}{{/each}}

Aby zbudować obiekt JSON.

 0
Author: Ditti,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-07-15 14:41:18