1, NVelocity 是 一般处理程序.ashx 和 前台页面模板的桥梁。 

2,我们现在建立一个简单的查询:  

    A,新建项目,把NVelocity.dll拉入项目中,并添加对其引用

  NVelocity 实现简单的 CIUD

  B,新建Common_Nvelocity.cs类, 借助NVelocity模板引擎把数据Data传递给对应的TemplateName页面

using Commons.Collections;
using NVelocity;
using NVelocity.App;
using NVelocity.Runtime;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;

namespace CIUD_NVelocitySample
{
    public class Common_Nvelocity
    {

        /// <summary>
        /// 通过NVelocity模板引擎,把Data数据参数中的数据传递到Template模板中
        /// </summary>
        /// <param name="TemplateName">模板页面名称</param>
        /// <param name="Data">参数数据</param>
        /// <returns>返回HTML直接渲染生成 页面</returns>
        public static string Template_Nvelocity(string TemplateName, object Data)
        {

            //创建NVlecocity模板引擎的实例对象
            VelocityEngine vlEngine = new VelocityEngine();

            //初始化实例对象,定义对象的部分属性
            ExtendedProperties props = new ExtendedProperties();
            props.AddProperty(RuntimeConstants.RESOURCE_LOADER, "file");//声明模板是在file中
            props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, System.Web.Hosting.HostingEnvironment.MapPath("~/Templates"));  //指定模板文件所在文件夹
            vlEngine.Init(props);

            //替换模板中的数据
            VelocityContext vltContext = new VelocityContext();
            vltContext.Put("data", Data);  //设置参数,在HTML模板中可以通过$Data读取数据


            //从文件中读取模板
            Template VltTemp = vlEngine.GetTemplate(TemplateName);
            //合并模板
            StringWriter writer = new StringWriter();
            VltTemp.Merge(vltContext, writer);

            //转化为字符串
            string html = writer.GetStringBuilder().ToString();

            return html;
        }
    }
}
View Code

相关文章:

  • 2021-09-01
  • 2021-04-11
  • 2021-12-02
  • 2021-08-29
  • 2022-01-19
  • 2021-06-17
  • 2021-05-21
  • 2022-01-10
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-09-17
  • 2021-08-23
  • 2021-04-13
  • 2021-08-19
  • 2021-08-06
相关资源
相似解决方案