views:

89

answers:

1

I am using the excellent jTemplates plugin to generate content.

Given a data object like this...

var data = {
 name: 'datatable',
 table: [
  {id: 1, name: 'Anne'},
  {id: 2, name: 'Amelie'},
  {id: 3, name: 'Polly'},
  {id: 4, name: 'Alice'},
  {id: 5, name: 'Martha'}
 ]
};

..I'm wondering if it is possible to directly specify an object in an array of objects using $T. (I'm hoping there is something like $T.table:3 available)

Currently the only way I can think of to access a specific object in an array is to do something like this...

{#foreach $T.table as record}

    {#if $T.record$iteration == 3}
        This is record 3!  Name:  {$T.record.name}
    {#/if}

{#/for}

However that seems clumsy...

Any suggestions?

Thanks

A: 

With the data you posted, you can do this with plain javascript :)

data.table[2].id   // 3
data.table[2].name // "Polly"

table is an immediate child of data, and this gets it's third child (arrays are 0 based).

The alternative, if I misunderstood and you want to search by id, would be something like this:

for(var i in data.table) {
  var o = data.table[i];
  if(o.id == 3) alert(o.name); // "Polly"
}
Nick Craver
Thanks, I'm trying to do this within jTemplates' templating language. But after a bit more experimentation turns out you can reference the value like so: $T.table[3].name. Doh! :)
Travis