Iteration with directives

To repeat an HTML node you need to use the <- notation

For example:

var directive = {
 'li':{
  'animal<-animals':{
   'span.name':'animal.name'
  }
 }
};

It means:

  • select the LI tag
  • repeat it for each record found in the 'animals' array or object
  • inside that LI, select the 'span' tag with the class 'name' and set its node value to the 'name' property of current loop item 'animal'

 

If you want to sort

You can add a "sort" function at the same level of the iteration directive 'i <- ii' i.e:

var directive = {
  'li':{
    'animal<-animals':{
      'span.name':'animal.name'
    },
    sort:function(a, b){
      return a.name > b.name ? 1 : -1;
    }
  }
};

The "a" and "b" parameters are items of the array, and the function will be used as a normal
Array.sort( function( a, b ){ ... }) style.
The "sort" function will work only when you loop on an array. If you add a sort function on an object properties loop, PURE will throw an exception.

 

If you want to filter

You can add a "filter" function at the same level of the iteration directive 'i <- ii' i.e:

var directive = {
  'li':{
    'animal<-animals':{
      'span.name':'animal.name'
    },
    filter:function(a){
      return (/^a/i).test(a.item.name);
    }
  }
};

The "a" parameter to the function is the same object that is passed to loops (with properties context, pos, item, items).
In the example above only the items with a name starting with an "a" or "A" will be kept.
If the function returns true the item is kept, if false the item won't be rendered.

The filter works on both arrays and object properties loops.

Note: a.pos will continue to indicate the current index of the innermost loop, even if items are skipped.

 

Here is an example: