NVelocity模板引擎快速起步教程

官方网站地址:http://www.castleproject.org/others/nvelocity/index.html

1. 在VS.Net2005中创建一个名为NVelocity.QuickStart的网站项目,并引用NVelocity.dll;
说明:NVelocity.dll 文件可以在Castle发行包里面找到

2. 在项目中增加一个名为"myTemplate.vm"的文本文件作为模板,其内容如下:
From: $from
To: $to
Subject: $subject

Hello $name

We're please to yada yada yada.

说明: NVelocity中的模板变量以$号标识,如上面模板中的 $from

3. 修改Default.aspx.cs的代码,如下:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;

using Commons.Collections;
using NVelocity;
using NVelocity.App;
using NVelocity.Context;
using NVelocity.Runtime;

namespace NVelocity.QuickStart
{
    
public partial class _Default : System.Web.UI.Page
    
{
        
protected void Page_Load(object sender, EventArgs e)
        
{
            
//创建VelocityEngine实例对象
            VelocityEngine velocity = new VelocityEngine();

            
//使用设置初始化VelocityEngine
            ExtendedProperties props = new ExtendedProperties();
            props.AddProperty(RuntimeConstants.RESOURCE_LOADER, 
"file");
            props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, Server.MapPath(
@"\"));
            velocity.Init(props);

            
//从文件中读取模板
            Template template = velocity.GetTemplate("myTemplate.vm");
            
            
//为模板变量赋值
            IContext context = new VelocityContext();
            context.Put(
"from""somewhere");
            context.Put(
"to""someone");
            context.Put(
"subject""Welcome to NVelocity");
            context.Put(
"name""John Doe");

            
//合并模板
            StringWriter writer = new StringWriter();
            template.Merge(context, writer);

            
//输出
            Response.Write(writer.ToString().Replace("\r\n""<br/>"));
        }

    }

}

现在,就可以运行并观看到结果了!非常简单,如果想深入了解NVelocity,可以查看其它相关资料。
posted @ 2008-05-04 17:53  '.Elvis.'  阅读(2177)  评论(0编辑  收藏  举报