Search code examples
javascriptjqueryjquery-templates

Using a variable in jQuery template with dynamic values


I am using jQuery template plugin (jquery.tmpl.min.js - v 1.0.0pre). My sample response object looks like this:

{
    "statusCode": "SUCCESS",
    "responseMessage": null,
    "response": [
        {
            "id": 92,
            "messageRead": false,
            "importance": null,
            "message": {
                "id": 86,
                "createdDate": 1414393557000,
                "messageType": "TESTTYPE",
                "subject": "test sub",
                "message": "test item",
                "fromOrg": 3,
                "accessCode": 2,
                "fromUserId": 1,
                "users": null,
                "read": false,
                "fromOrganizationName": null,
                "messageAttachment": [
                    {
                        "id": 5,
                        "createdDate": 1414393816000,
                        "name": "README"
                    }
                ]
            }
        }
    ]
}

In my template, while iterating over messageAttachment array, I need to access fromOrg inside the {{each messageAttachment}} loop.

{{if message.messageAttachment.length > 0 }}
    {{each message.messageAttachment}}
        \${name} <br/>
        ---- I need value of fromOrg here---
    {{/each}}
{{/if}}

How can I achieve this? My take on this is to declare a variable before looping messageAttachment array and use that variable inside the loop. I referred to this SO:

Can I declare local/temp variables within a jQuery template?

I tried to use this ${( $data.localVariable = 'SOMETHING' ),''} but unable to assign a runtime value instead of SOMETTHING.

Also, of there is any other way, please share. Any pointers appreciated. TIA.


Solution

  • As suggested by @adeneo, it can be directly accessed as message.fromOrg since there is no fromOrg inside messageAttachment array.