Search code examples
jqueryjtemplates

jTemplate Foreach does not render single row


I'm using the standard Main/Row jTemplate pattern but for some reason the foreach only works when there's more than one row (of StatusDetail). If it's a single row of data it doesn't render (the row inside the foreach that is. The part of the table before that does still render).

Data:
{
    "MG": {
        "Status": "In Transit",
        "StatusDetail": {
            "StatusCode": "Actual Pickup",
            "Date": {
                "@type": "actual",
                "#text": "11/13/2012 09:00"
                },
            "Location": "Mentor, OH "
        }
    }
}

jTemplate code:

{#template MAIN}
<table id="results_hdr" cellpadding="5" cellspacing="0">
    <tr>
        <td class="FieldLabels">Status</td>
        <td>{$T.MG.Status}</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td class="FieldLabels">Name</td>
        <td>{$T.MG.Name}</td>
    </tr>
    <tr><td colspan="6" style="background-color:White;"></td></tr>
    <tr>
        <td>Date</td>
        <td colspan="3">Detail</td>
        <td colspan="2">Location</td>
    </tr>
    {#foreach $T.MG.StatusDetail as SD}
        {#include ROW root=$T.SD}
    {#/for}
</table>
<br />
{#/template MAIN}
{#template ROW}
    <tr>
        <td>
            {$T.Date["#text"]}</td>
        <td colspan="3">
            {$T.StatusCode}</td>
        <td colspan="2">
            {$T.Location}</td>
    </tr>
{#/template ROW}

What am I missing?


Solution

  • You are trying to iterate through $T.MG.StatusDetail but it's not an array, so the {#foreach $T.MG.StatusDetail as SD} statement is not doing what you expect.

    Change your data to the following so that MG.StatusDetail is actually an array and it will work:

    Data:

    var data = {
        "MG": {
            "Status": "In Transit",
            "StatusDetail": [
                {
                    "StatusCode": "Actual Pickup",
                    "Date": {
                        "type": "actual",
                        "text": "11/13/2012 09:00"
                    },
                    "Location": "Mentor, OH "
                }
            ]
        }
    };
    

    Here's a DEMO.