Iterating Over Object Keys in Freemarker Templates with SuiteScript 2.1 Custom Data Source

61 Views Asked by At

In my Suitelet script I add custom data source to renderer. In Freemarker Template I am able to access the data. I am also able to list all the arrays of custom data source. Problem is, I cannot seem to be able to iterate over object keys.

Adding custom data source in Suitelet:

const obj1 = {
    currency: "EUR Currency",
    transactions: {
        EUR: [
            {
                parent_transaction: "101",
                total: "31.00"
            },
            {
                parent_transaction: "202",
                total: "650.00"
            },
            {
                parent_transaction: "303",
                total: "50.00"
            }
        ],
        USD: [
            {
                parent_transaction: "2",
                total: "32221.00"
            },
            {
                parent_transaction: "3",
                total: "64250.00"
            }
        ]
    }
}

const obj = JSON.stringify(obj1)

renderer.addCustomDataSource( {
    format: render.DataSource.JSON,
    alias: 'obj',
    data: obj
} )

Freemarker template:

<div>
    <#list obj.transactions?keys as currency>
    <h2>${currency}</h2>
    <table border="1">
        <thead>
            <tr>
                <th>Parent Transaction</th>
                <th>Total</th>
            </tr>
        </thead>
        <tbody>
            <#list obj.transactions[currency] as transaction>
            <tr>
                <td>${transaction.parent_transaction}</td>
                <td>${transaction.total}</td>
            </tr>
            </#list>
        </tbody>
    </table>
    </#list>
</div>

Example of the using data source successfully:

<p>First EUR transaction's total: ${obj.transactions.EUR[0].total}</p>

If I create a similar hash in the template, iterating works fine:

<#assign myHash = {"transactions": {"EUR": [{"number": 1}, {"number": 2}, {"number": 3}], "USD": [{"number": 4}, {"number": 5}, {"number": 6}]}}>

<table>
<#list myHash.transactions?keys as key>
<tr>
    <#list myHash.transactions[key] as txn>
    <td>${txn.number}</td>
</#list>
</tr>
</#list>
</table>

I also checked that obj.transactions has content before iterating. I have tried both format render.DataSource.OBJECT and render.DataSource.JSON. Why isn't iterating over object keys possible with custom data source?

1

There are 1 best solutions below

3
Brian Duffy On
<#assign things = obj.transactions?eval>
<#list things as thing>....