- Apache Velocity Home: http://velocity.apache.org/
I added following customization logic which convert String java object to Velocity Template object because I sometimes needed template object dynamically without creating template file.
(Please let me know if you have any other good ideas.)
Customization Example Steps
- get Velocity Source code from velocity.apache.org site.
- open org.apache.velocity.Template.java file.
- add java class import statements in Template.java
import org.apache.velocity.runtime.RuntimeSingleton;
import org.apache.velocity.runtime.RuntimeConstants;
import java.io.StringReader; - add customized constructor function of Template object as follows.
/*
customized constructor which convert String Object to Template Object.
@param pTemplateName is an template name
@param pTemplateString is String object you want to render
@return a velocity template object.
*/
public Template(String pTemplateName,String pTemplateString)
throws Exception
{
//Initialization
RuntimeSingleton.init();
setRuntimeServices(RuntimeSingleton.getRuntimeServices());
setName(pTemplateName);
//set encodeing if you need
//setEncoding(RuntimeConstants.ENCODING_DEFAULT);
data = null;
errorCondition = null;
StringReader stringReader=null;
BufferedReader bufferedReader=null;
try{
stringReader=new StringReader(pTemplateString);
bufferedReader=new BufferedReader(stringReader);
data = rsvc.parse(bufferedReader,name);
initDocument();
}catch(Exception e){
errorCondition=new Exception("Error occured while initializaing String Template, customization");
throw errorCondition;
}finally{
if(stringReader!=null){
stringReader.close();
}
if(bufferedReader!=null){
bufferedReader.close();
}
}
}
/*
End of Customization
*/ - compile new java file.
String testTemplate="Velocity Template Test";
Template template=new Template("TemplateName",testTemplate);
0 件のコメント:
コメントを投稿