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,可以查看其它相关资料。
posted @   蛤蟆  阅读(3030)  评论(4编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示