1 package org.apache.velocity.runtime.directive; 2 3 18 19 import java.io.Writer ; 20 import java.io.IOException ; 21 22 import java.util.Iterator ; 23 24 import org.apache.velocity.runtime.RuntimeServices; 25 import org.apache.velocity.runtime.RuntimeConstants; 26 27 import org.apache.velocity.context.InternalContextAdapter; 28 29 import org.apache.velocity.runtime.parser.node.Node; 30 31 import org.apache.velocity.exception.MethodInvocationException; 32 import org.apache.velocity.exception.ParseErrorException; 33 import org.apache.velocity.exception.ResourceNotFoundException; 34 35 import org.apache.velocity.util.introspection.Info; 36 37 45 public class Foreach extends Directive 46 { 47 50 public String getName() 51 { 52 return "foreach"; 53 } 54 55 58 public int getType() 59 { 60 return BLOCK; 61 } 62 63 68 private String counterName; 69 70 73 private int counterInitialValue; 74 75 85 private String elementKey; 86 87 90 protected Info uberInfo; 91 92 96 public void init(RuntimeServices rs, InternalContextAdapter context, Node node) 97 throws Exception 98 { 99 super.init(rs, context, node); 100 101 counterName = rsvc.getString(RuntimeConstants.COUNTER_NAME); 102 counterInitialValue = rsvc.getInt(RuntimeConstants.COUNTER_INITIAL_VALUE); 103 104 108 109 elementKey = node.jjtGetChild(0).getFirstToken().image.substring(1); 110 111 114 115 uberInfo = new Info(context.getCurrentTemplateName(), 116 getLine(),getColumn()); 117 } 118 119 122 public boolean render(InternalContextAdapter context, 123 Writer writer, Node node) 124 throws IOException , MethodInvocationException, ResourceNotFoundException, 125 ParseErrorException 126 { 127 130 131 Object listObject = node.jjtGetChild(2).value(context); 132 133 if (listObject == null) 134 return false; 135 136 Iterator i = null; 137 138 try 139 { 140 i = rsvc.getUberspect().getIterator(listObject, uberInfo); 141 } 142 catch(Exception ee) 143 { 144 System.out.println(ee); 145 } 146 147 if (i == null) 148 { 149 return false; 150 } 151 152 int counter = counterInitialValue; 153 154 158 159 Object o = context.get(elementKey); 160 Object ctr = context.get( counterName); 161 162 while (i.hasNext()) 163 { 164 context.put( counterName , new Integer (counter)); 165 context.put(elementKey,i.next()); 166 node.jjtGetChild(3).render(context, writer); 167 counter++; 168 } 169 170 174 175 if (ctr != null) 176 { 177 context.put(counterName, ctr); 178 } 179 else 180 { 181 context.remove(counterName); 182 } 183 184 185 189 190 if (o != null) 191 { 192 context.put(elementKey, o); 193 } 194 else 195 { 196 context.remove(elementKey); 197 } 198 199 return true; 200 } 201 } 202 | Popular Tags |