Skip to content

Instantly share code, notes, and snippets.

@rednaxelafx
Created November 20, 2010 17:11
Embed
What would you like to do?
Find out what's going on in Velocity, the interaction during rendering between a template and the context passed in. Bad news though, side-effects can happen which really forbids caching the variables locally.
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Arrays;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.context.Context;
/**
* Demonstrate interaction between a template and its context.
* Side-effects can arise from such interaction, which forbids
* a lot of optimizations if this behavior has to be kept.
*
* @author RednaxelaFX
*/
public class TestContext {
/**
* @param args
*/
public static void main(String[] args) throws Exception {
String template = "#set ($a = 123)#foreach ($i in [8..9])#end";
Context context = new VelocityContext() {
@Override
public Object internalGet(String key) {
Object value = super.internalGet(key);
System.out.println("read from " + key + " = " + value);
return value;
}
@Override
public Object internalPut(String key, Object value) {
System.out.println("written to " + key + " = " + value);
return super.internalPut(key, value);
}
@Override
public boolean internalContainsKey(Object key) {
boolean containsKey = super.internalContainsKey(key);
System.out.println("contains key " + key + " = " + containsKey);
return containsKey;
}
@Override
public Object[] internalGetKeys() {
Object[] keys = super.internalGetKeys();
System.out.println("got keys " + Arrays.toString(keys));
return keys;
}
@Override
public Object internalRemove(Object key) {
System.out.println("remove " + key);
return super.internalRemove(key);
}
};
Writer writer = new OutputStreamWriter(System.out);
Velocity.evaluate(context, writer, "error", template);
writer.close();
}
}
/*
Output:
written to a = 123
read from i = null
read from velocityCount = null
read from velocityHasNext = null
written to velocityCount = 1
written to velocityHasNext = true
written to i = 8
written to velocityCount = 2
written to velocityHasNext = false
written to i = 9
remove velocityCount
remove i
remove velocityHasNext
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment