Some Java Guy
Some Java Guy

Reputation: 5118

Multiple Instances of <C:if / Choose /When> condition to be made as one

1: I have a JSP with multiple html "TR's"

  <tr>'s

My page

  <% ...%>
  <html>
  ...
  <body>
  <table>
  <tr class="1"> This is first line</tr>
  <br/>
  <tr class="2"> This is Second line</tr>
  <br/>
  <tr class="3"> This is Third line</tr>
  <br/>
  <tr class="4"> This is Fourth line</tr>
  <br/>
  <tr class="5"> This is Fifth line</tr>
  <br/>
  ...
  </html>

2: Now I am getting user session (if logged in). Note>>:Using Liferay themeDisplay here

  <%String userEmail=themeDisplay.getUser().getEmailAddress();%>
  <c:set var="userEmail" value="<%=userEmail%>"></c:set>

3: I made a check to see if its guest or registered/logged in user.

Then the display changes for first and last "TR's" to logged-in user.

  <% ...%>
  <html>
  ...
  <body>
  <table>
  <c:if test="${not empty userEmail}">      
  <tr class="1"> This is first line for registered user</tr>
  <c:if test="${empty userEmail}">      
  <tr class="1"> This is first line</tr>
  <br/>
  <tr class="2"> This is Second line</tr>
  <br/>
  <tr class="3"> This is Third line</tr>
  <br/>
  <tr class="4"> This is Fourth line</tr>
  <br/>
  <c:if test="${not empty userEmail}">      
  <tr class="5"> This is Fifth line for registered user</tr>
  <c:if test="${empty userEmail}">      
  <tr class="5"> This is Fifth line</tr>
  <br/>
  ...
  </html>

This is working fine!!

My question>>>>>If I want to make this check as constant of some sort, which would not be repeated many times on the JSP/HTML page. What is to be done ???

  <c:if> //to be declared only once. And called which ever <TR> needs a check??

Upvotes: 1

Views: 3235

Answers (1)

Anthony Grist
Anthony Grist

Reputation: 38345

A few alternatives:

  1. Use c:set to set a registered variable on the page, which you use for a c:choose.

    <c:set var="registered" value="${not empty userEmail}"/>
    <c:choose>
    <c:when test="${registered}">
    <tr class="1"> This is first line for registered user</tr>
    </c:when>
    <c:otherwise>
    <tr class="1"> This is first line</tr>
    </c:otherwise>
    </c:choose>

  1. Write the first and last lines as blank table rows, then use a c:choose to run javascript to insert the data you want.

    <table>
    <tr id="firstRow"></tr>
    ...
    <tr id="lastRow"></tr>
    </table>

    <c:choose>
    <c:when test="${not empty userEmail}">
    <script>
    document.getElementById('firstRow').innerHTML = 'This is first line for registered user';
    document.getElementById('lastRow').innerHTML = 'This is Fifth line for registered user';
    </script>
    </c:when>
    <c:otherwise>
    <script>
    document.getElementById('firstRow').innerHTML = 'This is first line';
    document.getElementById('lastRow').innerHTML = 'This is Fifth line';
    </script>
    </c:otherwise>
    </c:choose>

Upvotes: 1

Related Questions