この例は、JavaでVelocityを使用してページを生成する方法を示しています。
Hello $name!
コードは、コンテキスト内の変数を設定します。 コンテキストはテンプレートに渡されます。 レンダリングはコンテキストを使用して処理されます。
import static org.junit.Assert.assertEquals;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
public class VelocitySimple {
public static void main(String[] argv){
// Source directory
String sourceDirectory = "V:/tmp/velocity/";
// Create the velocity engine
VelocityEngine ve = new VelocityEngine();
ve.setProperty( "resource.loader", "file");
ve.setProperty( "file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.FileResourceLoader");
ve.setProperty( "file.resource.loader.path", sourceDirectory);
ve.setProperty( "file.resource.loader.cache", true);
ve.setProperty( "file.resource.loader.modificationCheckInterval", "2");
ve.init();
// Get the template
Template t = ve.getTemplate( "example.vm" );
// Create the
VelocityContext context = new VelocityContext();
context.put("name", "World");
try {
// Create the output file
Writer out = new BufferedWriter(new OutputStreamWriter( new FileOutputStream( new File( sourceDirectory + "example.txt" ) ), "UTF8") );
t.merge( context, out);
out.close();
} catch ( Exception e ){
e.printStackTrace();
}
}
}
Hello World!
コードはまず、ファイルリソースローダーを使用して VelocityEngine を初期化します。 これは、テンプレートを強化するディレクトリにローダーパスを設定します。 次に、getTemplateメソッドを使用してテンプレートディレクトリからテンプレートを取得します。 変数のセットは、 VelocityContext に設定されています。ここではname = Worldです。そのコンテキストは、出力ファイルを生成するマージメソッドに渡されます。 $ nameとして定義された変数は、テンプレートで置き換えられました。