简体   繁体   中英

Hogan.js - reference an item with a specific index

I wish to have a section only for a particular item in an array. Eg:

var items = ['first','second']

Eg:

{{#items[1]}}
   Slightly different styling for the second item, for no difference other than it's the second item.
{{/items[1]}}

I've tried:

{{#items.1}}
  Slightly different styling for the second item, for no difference other than it's the second item.
{{/items.1}}

As well as:

{{#items}}
  {{#0}}
     Slightly different styling for the second item, for no difference other than it's the second item.
  {{/0}}
{{/items}}

But neither of those work.

I really don't want to have to make an object like:

{'1':'first','2':'second'}

Because that's just nasty.

Any ideas?

before i give you some suggestions/work-arounds like you state, its just some silly styling, and as such has nothing to do with rendering or with the data. If it has a meaning in that sense you should realy add that to your data so it represents ts structure better.

Mustache is a logic-less templating language, and if you feel you need the Mustache language, you relaly should keep it as logic-less as possible, otherwise just use Handlebars

css

you could use css for that; altho not in IE<9 note the lack of the "n" in the filter

.selector:nth-child(2) {
    some: styling;
}

change data

secondly, you could change the data before you pass it to Hogan either as part of the data-processing in the controller or as the js frameworks sometimes call them view-controllers, changing it into an object is like you say not the best way, you could make it an array of array's

[ [1,'first'], [2, 'second'] ]

Handlebars

if you dont need Hogan, Handlebars has an {{@index}} for the current index

functions

as an alternative method to change your input data, you can create a helper function to handle that logic for you, but again this isnt really logic, its just visual. and mustache is a logic-less templating language, so be careful when starting with these kinds of

var items = ['first','second'];
var data = {items:items};

data.second= (function () {
    var i=0;
    return function () {
        return i++ === 1; //index 1 being the second item in an array
    }
}());

and then use the second helper

{{#items}}
    {{#second}}
    Slightly different styling for the second item, for no difference other than it's the second item.
    {{/second}}
{{/items}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM