Hello, NVelocity World!
Posted on 2月 12th, 2012 by cx20
NVelocity
NVelocity は Java 用のテンプレートエンジン「Velocity」の .NET 実装である。
ソースコード(テンプレート)
<html>
<head>
<title>Hello, World!</title>
</head>
<body>
<p>Hello, $message World!</p>
</body>
</html> |
<html>
<head>
<title>Hello, World!</title>
</head>
<body>
<p>Hello, $message World!</p>
</body>
</html>
ソースコード(C#)
using System;
using System.IO;
using System.Diagnostics;
using Commons.Collections;
using NVelocity;
using NVelocity.App;
using NVelocity.Context;
public partial class _Hello : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
VelocityEngine velocity = new VelocityEngine();
VelocityContext context = new VelocityContext();
StringWriter sw = new StringWriter();
try
{
String properties = Server.MapPath("nvelocity.properties");
velocity.Init(properties);
Template template = velocity.GetTemplate("hello.vm");
context.Put("message", "NVelocity");
template.Merge(context, sw);
Response.Write(sw.GetStringBuilder().ToString());
}
catch( Exception ex )
{
Debug.WriteLine("Exception: " + ex.Message);
}
}
} |
using System;
using System.IO;
using System.Diagnostics;
using Commons.Collections;
using NVelocity;
using NVelocity.App;
using NVelocity.Context;
public partial class _Hello : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
VelocityEngine velocity = new VelocityEngine();
VelocityContext context = new VelocityContext();
StringWriter sw = new StringWriter();
try
{
String properties = Server.MapPath("nvelocity.properties");
velocity.Init(properties);
Template template = velocity.GetTemplate("hello.vm");
context.Put("message", "NVelocity");
template.Merge(context, sw);
Response.Write(sw.GetStringBuilder().ToString());
}
catch( Exception ex )
{
Debug.WriteLine("Exception: " + ex.Message);
}
}
}
実行方法
ディレクトリ構成
/Hello … 公開用フォルダ
/Hello.aspx
/Hello.aspx.cs
/nvelocity.properties … NVelocity 設定ファイル
/Web.config … ASP.NET 構成ファイル
/bin
/NVelocity.dll
/templates … テンプレート配置場所
/hello.vm
1. テンプレートの配置
templates
2. nvelocity.properties の記載 |
ディレクトリ構成
/Hello … 公開用フォルダ
/Hello.aspx
/Hello.aspx.cs
/nvelocity.properties … NVelocity 設定ファイル
/Web.config … ASP.NET 構成ファイル
/bin
/NVelocity.dll
/templates … テンプレート配置場所
/hello.vm
1. テンプレートの配置
templates
2. nvelocity.properties の記載
resource.loader = file
file.resource.loader.class = NVelocity.Runtime.Resource.Loader.FileResourceLoader
file.resource.loader.path = C:\home\edu\vs2010\vc10#\Hello\templates
file.resource.loader.cache = true
file.resource.loader.modificationCheckInterval = 2 |
resource.loader = file
file.resource.loader.class = NVelocity.Runtime.Resource.Loader.FileResourceLoader
file.resource.loader.path = C:\home\edu\vs2010\vc10#\Hello\templates
file.resource.loader.cache = true
file.resource.loader.modificationCheckInterval = 2
3. ブラウザで表示
http://localhost/Hello/Hello.aspx |
3. ブラウザで表示
http://localhost/Hello/Hello.aspx
実行結果
Hello, NVelocity World!
Tags: NVelocity
Categories: ASP.NET, NVelocity, Velocity