How to use for loop in transactional message center | Community
Skip to main content
Level 2
February 8, 2023
Solved

How to use for loop in transactional message center

  • February 8, 2023
  • 1 reply
  • 1012 views

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.

This post is no longer active and is closed to new replies. Need help? Start a new post to ask your question.
Best answer by akshaaga

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.

1 reply

akshaaga
Adobe Employee
akshaagaAdobe EmployeeAccepted solution
Adobe Employee
February 9, 2023

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.