NVelocity模板引擎快速起步教程

本文将通过编写一个简单的示例程序,帮助刚接触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,可以查看其它相关资料。

转载于:https://www.cnblogs.com/netflu/archive/2008/03/04/1089949.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值