This tutorial is about #set element in velocity template.
Please click this link for Velocity Dependency & Introduction.
#set element is being used by developer to create new variable directly in velocity template.
Find below Syntax:
#set($i = 0)
#set($name = "omtlab")
#set($count = 10.12)
Find below template for this example :
set.vm
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
#set($i = 0) i : $i #set($count = $i+1) count : $count #set($name = "omtlab") name : $name #set($fromJava = $someValue) From Java : $fromJava #set($joinString = "$fromJava$name") Join Two String : $joinString #set($sites = ["omtlab.com","google.com"]) #foreach($site in $sites) Site $count : $site #set($count = $count+1) #end |
Example Code :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
package com.omt.velocity.example; import java.io.StringWriter; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.Velocity; public class SetExample { public SetExample() { } public static void main(String... args) { setExample(); } public static void setExample() { Velocity.init(); VelocityContext context = new VelocityContext(); context.put("someValue", "This is from java code"); Template t = Velocity.getTemplate("set.vm"); StringWriter sw = new StringWriter(); t.merge(context, sw); System.out.println(sw.toString()); } } |
Output :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
i : 0 count : 1 name : omtlab From Java : This is from java code Join Two String : This is from java codeomtlab Site 1 : omtlab.com Site 2 : google.com |