3

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>  

3 Answers 3

5

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>
Sign up to request clarification or add additional context in comments.

2 Comments

Great idea! I made a small modification by removing the counter all-together, setting class to activeLI when defining it then emptying the value after it is used the first time. Many thanks for the idea.
Thanks, and nice improvement there!
1

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>

Comments

0

Have you considered using <apex:dataList>? I think it may accomplish what you're looking to do.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.