当前位置:Gxlcms > PHP教程 > velocity第五个应用例子---获得当前迭代的索引

velocity第五个应用例子---获得当前迭代的索引

时间:2021-07-01 10:21:17 帮助过:20人阅读

velocity第五个应用例子---获得当前迭代的索引

  1. #foreach($key in $map.keySet())
  2. $velocityCount > $key : $map.get($key)
  3. #end
  4. $velocityCount获得当前迭代索引
  5. velocityCount变量名可以通过directive.foreach.counter.name属性修改,
  6. 如:directive.foreach.counter.name=index,以后可以通过$index进行访问。
  7. 迭代的索引默认从1开始,我们可以通过directive.foreach.inital.value=0进行修改。

控台输出

  1. 1> key4 : value4
  2. 2> key3 : value3
  3. 3> key2 : value2
  4. 4> key1 : value1

修改索引变量名

在属性文件增加配置

  1. #修改索引变量名
  2. directive.foreach.counter.name=index
  3. index.vm
  4. #foreach($key in $map.keySet())
  5. $index
  6. >>>
  7. $key : $map.get($key)
  8. #end
  9. #修改迭代索引的默认值
  10. directive.foreach.counter.initial.value=0

模板

  1. #foreach($key in $map.keySet())
  2. $index
  3. >>>
  4. $key : $map.get($key)
  5. #end

控台输出

  1. 0 >>> key4 : value4
  2. 1
  3. >>> key3 : value3
  4. 2
  5. >>> key2 : value2
  6. 3
  7. >>> key1 : value1
  8. //2 Create aContext object
  9. VelocityContextcontext = new VelocityContext();
  10. //3 Add you dataobjects to this context
  11. Map<String,String>map = new HashMap<String,String>();
  12. map.put("key1","value1");
  13. map.put("key2","value2");
  14. map.put("key3","value3");
  15. map.put("key4","value4");
  16. context.put("map",map);
  17. //4 Choose atemplate
  18. Templatetemplate = Velocity.getTemplate("index.vm");
  19. //5 Merge thetemplate and you data to produce the output
  20. StringWriter sw= new StringWriter();
  21. template.merge(context,sw);
  22. sw.flush();
  23. System.out.println(sw.toString());

模板

  1. #foreach($keyin $map.keySet())
  2. $velocityCount > $key : $map.get($key)
  3. #end
  4. =============
  5. #foreach($keyin $map.keySet())
  6. $index >>>
  7. $key :$map.get($key)
  8. #end

以上就是velocity第五个应用例子---获得当前迭代的索引的内容,更多相关内容请关注PHP中文网(www.gxlcms.com)!

人气教程排行