How to detect first or last iteration of apex:repeat

I currently have some VisualForce which uses an <apex:repeat/> element and inserts commas in between the items like so:

<apex:variable var="idx" value="{!0}"/>
<apex:repeat value="{!items}" var="item">
    <apex:outputPanel rendered="{!NOT(idx == 0)}">, </apex:outputPanel>
        <apex:outputText value="{!item.Name}" />
    <apex:variable var="idx" value="{!idx + 1}" />

However, today I noticed in the documentation that this is explicitly unsupported and is a case of undefined behavior:

<apex:variable> does not support reassignment inside of an iteration component, such as <apex:dataTable> or <apex:repeat>. The result of doing so, e.g., incrementing the <apex:variable> as a counter, is unsupported and undefined.


So my question is this: if the syntax I’m using is not supported (even though it does work), then how can I render this comma-delimited data in a way that is supported, using only VisualForce? Is this possible?


I rethought and this seems the best way so deleting the previous contents:

  1. Create a map<account,index>

  2. Put the account, index and also populate the last index in your method, and check if the index = last index and render the ,


<apex:page controller="testing_repeat_controller" sidebar="false">
<apex:repeat value="{!Itemsforuser}" var="item">    
    <apex:outputPanel >
        <apex:outputText value="{!item.Name}"/>
        {!IF(account_index_map[item] == lastindexofaccount,'',',')}


public class testing_repeat_controller {
    public integer indexofaccount {get;set;}
    public integer lastindexofaccount {get;set;}
    public map<account,integer> account_index_map {get;set;} 
    public testing_repeat_controller(){
        indexofaccount      = 0;
        lastindexofaccount  = 0;
        account_index_map = new map <account,integer>();
    public List<account> getItemsforuser(){
        list<account> acc_list = [select id,name from account limit 10];
        lastindexofaccount = acc_list.size();
        for(account a: acc_List){        
            indexofaccount = indexofaccount +1;
        return acc_List;


abc ,abc ,TEST ,test123 ,abc ,abc ,abc ,TEST ,Test_Pass ,abc

Source : Link , Question Author : user2221343 , Answer Author : Adrian Larson

Leave a Comment