Displaying table headers and values all from JSON data

76 views
Skip to first unread message

imbibinebe

unread,
Mar 16, 2012, 11:52:23 AM3/16/12
to JavaScript Templates Engine PURE
Hi,
My JSON data comes from a database and can look like this:

{
"users":
[
{"head1": "v11", "head2": "v12"},
{"head1": "v21", "head2": "v22"}
]
}

If I want to display the html table:

[ head1 ] [ head2 ]
[ v11 ][ v12 ]
[ v21 ][ v22 ]

with this html:

<table>
<thead>
<tr>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
</tr>
</tbody>
</table>

the following directive works nice:

{
"thead > tr > th":
{
"user1 <- users.0":
{
".":user1.pos
}
},
"tbody":
{
"user < users":
{
"tr > td":
{
"value <- user":
{
".":value
{
}
}
}
}

Now, unfortunatly, in some cases, the data might look like this:

[
{ 'head1':"v11" , 'head2': "v12"},
{ 'head1':"v21" , 'head2': "v22"}
]

No more 'users' property, it's only an array. I didn't find the good
directive (if it exists ;) to display the same table.
I tried this:

{
"thead > tr > th":
{
"fisrtline <- context.0":
{
".":fisrtline.pos
}
},
"tbody":
{
"line < context":
{
"tr > td":
{
"value <- line":
{
".":value
{
}
}
}
}

but it seems i can't access a single object with context.0 ...
does anyone have an idea ?

Mic (BeeBole)

unread,
Mar 22, 2012, 4:18:53 AM3/22/12
to Pure-Unobtrusive...@googlegroups.com
If the root of the JSON is the array, you can write it like this:


    "fisrtline <-": 
    { 
      ".":fisrtline.pos 
    } 
  }, 

imbibinebe

unread,
Mar 22, 2012, 4:50:06 AM3/22/12
to JavaScript Templates Engine PURE
Yes, but it's not what want to do. In order to display my table
headers i need to access the first element of the array and loop on
its keys using 'pos'.
Just like I do with "user1 <- users.0" in my working example ;) But
"arrayFisrt <- context.0" doesn't work ...

Mic (BeeBole)

unread,
Mar 24, 2012, 4:46:05 PM3/24/12
to JavaScript Templates Engine PURE
I've changed pure.js to allow context.something as a loop root.
Your example works. My test suite and our webapp too.
Insure you have the 2.73 and let me know.

Cheers,

imbibinebe

unread,
Mar 25, 2012, 3:36:09 PM3/25/12
to JavaScript Templates Engine PURE
Brilliant ! Thank you so much Mic, it's working perfectly :)
Reply all
Reply to author
Forward
0 new messages