Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VisualForce - conditional html tags

I am trying to apply a different style to the first element in a list.

I am currently attempting to use a counter to apply the li with a class only when cnt==0 but I cannot include < > brackets in an OutputText tag. Is there any way to escape the brackets or insert the class into an <li> tag using a condition?

I know this could be done after the fact using JavaScript but I'd rather avoid it.

<apex:variable var="cnt" value="{!0}" /> 
<apex:repeat value="{!items}" var="item" >
    <!-- only render the class if it is the first element -->
    <apex:OutputText value="<li class="activeLI">" rendered="{!cnt==0}" />
    <apex:OutputText value="<li>" rendered="{!cnt!=0}" />        

        <img src="{!$Resource[item.Image__c]}" width="85" height="90"/>
    </li>
    <apex:variable var="cnt" value="{!cnt+1}"/>
</apex:repeat>  
like image 294
UserIsStuck Avatar asked Feb 16 '26 16:02

UserIsStuck


2 Answers

Visualforce is strict, every element must have an opening and closing tag or must be self-closing. When compiled, Visualforce will complain as it will only see the closing "li" tag and not the conditional opening "li" tag, one solution is to make the class name a variable as follows:

<apex:variable var="cnt" value="{!0}" />
<apex:variable var="class" value=""/>
<apex:repeat value="{!items}" var="item" >
  <apex:variable var="class" value="activeLI" rendered="{!cnt==0}"/>
  <apex:variable var="class" value="" rendered="{!cnt!=0}"/>
    <li class="{!class}">
      ...
    </li>
  <apex:variable var="cnt" value="{!cnt+1}"/> 
</apex:repeat>
like image 112
manubkk Avatar answered Feb 19 '26 05:02

manubkk


Have you consider using a CSS selector? Here's an example on how to style the first element of a list.

<style>
ul.myList > li:first-child {color : red}
</style>

<ul class="myList">
  <li>this is red</li>
  <li>this has default formatting</li>
</ul>
like image 25
Acuariano Avatar answered Feb 19 '26 07:02

Acuariano



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!