aspx NVelocity 模板使用
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了aspx NVelocity 模板使用相关的知识,希望对你有一定的参考价值。
1.新建webform项目
2.引用NVelocity.dll
3.添加UserInfo.aspx,并删除其中的代码,只留第一句话
4.添加实体类
public class UserInfoEntity { public int UserId { get; set; } public string UserName { get; set; } }
5.在UserInfo.aspx.cs的load中写
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Commons.Collections; using NVelocity; using NVelocity.App; using NVelocity.Context; using NVelocity.Runtime; public partial class UserInfo : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { List<UserInfoEntity> list = new List<UserInfoEntity>(); list.Add(new UserInfoEntity() { UserId = 1, UserName = "chm1" }); list.Add(new UserInfoEntity() { UserId = 2, UserName = "chm2" }); //1.创建VelocityEngine实例对象 VelocityEngine engine = new VelocityEngine(); //2.读取模板路径,可以定义几套模板利于动态换肤 string path = Server.MapPath(@"Template\\UserInfo.vm"); string tmpPath = path.Substring(0, path.LastIndexOf(@"\\")); string filePath = path.Substring(path.LastIndexOf(@"\\") + 1); //3.使用设置初始化VelocityEngine ExtendedProperties props = new ExtendedProperties(); props.AddProperty(RuntimeConstants.RESOURCE_LOADER, "file"); props.AddProperty(RuntimeConstants.INPUT_ENCODING, "utf-8"); props.AddProperty(RuntimeConstants.OUTPUT_ENCODING, "utf-8"); props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, tmpPath); engine.Init(props); //4.模板引擎从文件中读取模板 Template tmp = engine.GetTemplate(filePath); //Template tmp = engine.GetTemplate(@"UserInfo.html"); //5.为模板变量赋值 IContext context = new VelocityContext(); context.Put("Title", "测试"); context.Put("listUserInfo", list); //6.合并模板和流写出器 StringWriter write = new StringWriter(); tmp.Merge(context, write); Response.Write(write.ToString()); } }
6.在项目下新建文件夹(Template)
7.在Template下新建UserInfo.html页面
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>$Title</title> </head> <body> <table> #foreach($item in $listUserInfo) <tr><td>$item.UserId</td><td>$item.UserName</td></tr> #end </table> </body> </html>
8.把UserInfo.html的后缀改成vm
以上是关于aspx NVelocity 模板使用的主要内容,如果未能解决你的问题,请参考以下文章