Expand my Community achievements bar.

SOLVED

How to use for loop in transactional message center

Avatar

Level 2

Hi,

 

I have written below code in transactional message center email template.

 

 <% var ctx = XML(rtEvent.ctx); %>  
<% for(var i=1;i <=rtEvent.ctx.firstName.length;i++){%>                                                                                
<%=escapeXmlStr(rtEvent.ctx.firstName[i])%>                                     
<% }%>

 

and below is the ctx format which passing from postman application-

<ctx>
<firstName1>ABC</firstName1>
<age1>30</age1>
<firstName2>PQR</firstName2>
<age2>40</age2>
</ctx>

 

I am expecting output in below format-

 

ABC 30
PQR 40

 

What code should I write in template to display this output?

 

Thanks in advance.

1 Accepted Solution

Avatar

Correct answer by
Employee Advisor

Hi @tejashri12 -

 

You can try using the below code that should display the desired output:

 

<% var ctx = XML(rtEvent.ctx); %>
<% for(var i=1;i <= ctx.childNodes.length/2;i++){%>
<%=escapeXmlStr(ctx["firstName"+i])%> <%=escapeXmlStr(ctx["age"+i])%>
<% }%>

 

In this code, the childNodes property of the ctx object is used to determine the number of elements in the ctx object.

Since each child node represents one firstName and one age element, the number of child nodes is divided by 2 to get the number of firstName elements. The code then loops over this number and uses square bracket notation to access the firstName and age elements for each iteration.

Finally, the escapeXmlStr function is used to escape any characters that have a special meaning in XML, to ensure that the output is properly formatted.

View solution in original post

1 Reply

Avatar

Correct answer by
Employee Advisor

Hi @tejashri12 -

 

You can try using the below code that should display the desired output:

 

<% var ctx = XML(rtEvent.ctx); %>
<% for(var i=1;i <= ctx.childNodes.length/2;i++){%>
<%=escapeXmlStr(ctx["firstName"+i])%> <%=escapeXmlStr(ctx["age"+i])%>
<% }%>

 

In this code, the childNodes property of the ctx object is used to determine the number of elements in the ctx object.

Since each child node represents one firstName and one age element, the number of child nodes is divided by 2 to get the number of firstName elements. The code then loops over this number and uses square bracket notation to access the firstName and age elements for each iteration.

Finally, the escapeXmlStr function is used to escape any characters that have a special meaning in XML, to ensure that the output is properly formatted.