user2142786
user2142786

Reputation: 1482

how to increment counter between between asterisk in jsp using advance if else?

I want to create name of my class dynamically for this in for each loop i'm doing this. I am increment i for each for loop and using this i in class name. Here is my code.

<% int i=1;
for (Navigation.Element e: nav) {%>
<a href="#">
<%= e.hasChildren() ? "<i class=\"menu-icon menu-icon-"i++"\"></i>" : "" %> Link </a>

<%}%>

As i++ will not work because i is a variable need to be in between + + like +i+ i want to increment i and do this in single line.

Is it possible ?

Upvotes: 0

Views: 259

Answers (2)

folkol
folkol

Reputation: 4883

Just add parentheses:

<% int i=1;
for (Navigation.Element e: nav) {%>
<a href="#">
<%= e.hasChildren() ? "<i class=\"menu-icon menu-icon-" + (i++) + "\"></i>" : "" %> Link </a>
<%}%>

(It is technically possible to skip them, but the resulting code will be more confusing.)

Examples:

"<i class=\"menu-icon menu-icon-" + i++ + "\"></i>"
"<i class=\"menu-icon menu-icon-" +i+++ "\"></i>"

Upvotes: 1

W&#252;rgspa&#223;
W&#252;rgspa&#223;

Reputation: 4820

As a one-liner this should work:

<%= e.hasChildren() && (i++>0) ? "<i class=\"menu-icon menu-icon-" + i + "\"></i>" : "" %> Link </a>

Upvotes: 0

Related Questions