Skip to content

Instantly share code, notes, and snippets.

@mumumu
Created June 21, 2011 22:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mumumu/1039154 to your computer and use it in GitHub Desktop.
Save mumumu/1039154 to your computer and use it in GitHub Desktop.
import java.io.StringWriter;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.Template;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.MethodInvocationException;
import java.util.Vector;
/**
*
* Apache Velocity の使い方を示したSnippet
*
* test/mytemplate.vm の中身は以下のとおり
*
* <code>
* Hello $name !
* #foreach ($elm in $vector)
* <li>$elm</li>
* #end
* </code>
*
* 出力は以下の通り
*
* Hello Velocity !
* <li>hoge</li>
* <li>fuga</li>
*
*/
public class VelocityTest {
public static void main(String[] args) {
try
{
// クラスパスを起点にしてテンプレートファイルを探す
// Velocity にグローバルなPropertyを設定するときは
// init() を呼び出す前に行うこと
Velocity.setProperty("resource.loader", "class");
Velocity.setProperty("class.resource.loader.class",
"org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"
);
Velocity.init();
VelocityContext context = new VelocityContext();
// 配列を設定してみる
Vector v = new Vector();
v.addElement("hoge");
v.addElement("fuga");
context.put( "vector", v);
// 文字列を設定
context.put( "name", new String("Velocity") );
// テンプレートを指定してオブジェクトを取得
Template template = null;
template = Velocity.getTemplate("test/mytemplate.vm");
StringWriter sw = new StringWriter();
// テンプレートと変数をマージして出力
template.merge( context, sw );
System.out.println(sw);
}
catch( ResourceNotFoundException rnfe )
{
// couldn't find the template
}
catch( ParseErrorException pee )
{
// syntax error: problem parsing the template
}
catch( MethodInvocationException mie )
{
// something invoked in the template
// threw an exception
}
catch( Exception e )
{}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment