NVelocity的使用

前段时间,在项目中运用了.NET模板引擎NVelocity.为了加深对这个模板引擎的理解,为了方便在以后的项目中加以利用,特来总结一下。

NVelocity是什么?

NVelocity是一个基于.NET的模板引擎(template engine)。它允许任何人仅仅简单的使用模板语言(template language)来引用由.NET代码定义的对象。
当nVelocity 应用于web开发时,界面设计人员可以和.NET程序开发人员同步开发一个遵循MVC架构的web站点,也就是说,页面设计人员可以只关注页面的显示效 果,而由.NET程序开发人员关注业务逻辑编码。NVelocity将.NET代码从web页面中分离出来,这样为web站点的长期维护提供了便利,同时也为我们在aspx之外又提供了一种可选的方案。
NVelocity的能力远不止web站点开发这个领域,例如,它可以从模板(template)产生SQL和PostScript、XML,它也可以被当作一个独立工具来产生源代码和报告,或者作为其他系统的集成组件使用。 NVelocity也可以为很多web开发架构提供模板服务(template service)。我们的系统就提供一个模板服务的方式允许一个web应用以一个真正的MVC模型进行开发。

NVelocity的用法:

1.首先在项目中引用程序集NVelocity.dll

image

这样在项目的引用中出现NVelocity

image

 

2.接着添加帮助类NVelocityHelp.cs文件。

image

ExpandedBlockStart.gif View Code
  1  using NVelocity;
  2      using NVelocity.App;
  3      using NVelocity.Context;
  4      using NVelocity.Runtime;
  5      public  class NVelocityHelper
  6     {
  7          private VelocityEngine velocity =  null;
  8          private IContext context =  null;
  9 
 10 
 11          ///   <summary>
 12           ///  无参数构造函数
 13           ///   </summary>
 14           public NVelocityHelper()
 15         {
 16             Init();
 17         }
 18 
 19          ///   <summary>
 20           ///  初始话NVelocity模块
 21           ///   </summary>
 22           public  void Init()
 23         {
 24              // 创建VelocityEngine实例对象
 25              velocity =  new VelocityEngine();
 26             velocity.Init();
 27              // 为模板变量赋值
 28              context =  new VelocityContext();
 29         }
 30 
 31          ///   <summary>
 32           ///  初始话NVelocity模块
 33           ///   </summary>
 34           ///   <param name="templatePath"> 模板路径 </param>
 35           public  void Init( string templatDir)
 36         {
 37              // 创建VelocityEngine实例对象
 38              velocity =  new VelocityEngine();
 39 
 40             ExtendedProperties props =  new ExtendedProperties();
 41 
 42             props.AddProperty(RuntimeConstants.RESOURCE_LOADER,  " file ");
 43             props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, HttpContext.Current.Server.MapPath(templatDir));
 44             props.AddProperty(RuntimeConstants.INPUT_ENCODING,  " UTF-8 ");
 45             props.AddProperty(RuntimeConstants.OUTPUT_ENCODING,  " UTF-8 ");
 46 
 47             velocity.Init(props);
 48              // 为模板变量赋值
 49              context =  new VelocityContext();
 50         }
 51 
 52          public  string ConvertByFile( string filename)
 53         {
 54             StringWriter writer =  new StringWriter();
 55             Template template = velocity.GetTemplate(filename,  " UTF-8 ");
 56 
 57             template.Merge(context, writer);
 58 
 59              return writer.GetStringBuilder().ToString();
 60         }
 61 
 62          ///   <summary>
 63           ///  给模板变量赋值
 64           ///   </summary>
 65           ///   <param name="key"> 模板变量 </param>
 66           ///   <param name="value"> 模板变量值 </param>
 67           public  void Put( string key,  object value)
 68         {
 69             context = context ??  new VelocityContext();
 70             context.Put(key, value);
 71         }
 72 
 73          ///   <summary>
 74           ///  输出根据模板内容解析后的html代码
 75           ///   </summary>
 76           ///   <param name="templateContent"></param>
 77           public  void Display( string templateContent)
 78         {
 79             StringWriter writer =  new StringWriter();
 80 
 81              try
 82             {
 83                 velocity.Evaluate(context, writer,  null, templateContent);
 84                 HttpContext.Current.Response.Clear();
 85                 HttpContext.Current.Response.Write(writer.GetStringBuilder().ToString());
 86             }
 87              catch (Exception ex)
 88             {
 89                 HttpContext.Current.Response.Clear();
 90                 HttpContext.Current.Response.Write(ex.Message.ToString());
 91             }
 92 
 93             HttpContext.Current.Response.Flush();
 94         }
 95 
 96          ///   <summary>
 97           ///  返回解析后的html内容
 98           ///   </summary>
 99           ///   <param name="templateContent"></param>
100           ///   <returns></returns>
101           public  string Convert( string templateContent)
102         {
103             StringWriter writer =  new StringWriter();
104             velocity.Evaluate(context, writer,  null, templateContent);
105 
106              return writer.GetStringBuilder().ToString();
107         }
108     }

 

 

3.在controller里面的action里面调用替换页面中模板引擎变量的方法,如下面index里面的Convert(“index”),这里的MembershipController继承下面的MembershipBaseController

MembershipController.cs

public ActionResult Index(int id, int themeId=0, int styleId=0)
          {
              this.MembershipId = id;
              this._ThemeId = themeId;
              this._StyleId = styleId;
              return Convert("index");
          }

 

4.替换页面中模板引擎变量的方法在MembershipBaseController.cs定义

  public ActionResult Convert(string code, string detailName = "", string detailKeyWords = "", string detailDesc = "")

       //引入变量LResult ,判断用户是否是最新加盟的企业(是否是诚信用户)

       bool  LResult = this.IsLatestJoinCompanyLogo(MembershipId);
        //引入变量VResult,判断用户是否是VIP用户(分为企业VIP或者是政务VIP)
       bool  VResult = this.IsVipUser(MembershipId);

//往NVelocity引擎里面引入两个变量,用于在前台页面进行判断是否是诚信用户和VIP用户

Put方法的前一个是键key,后一个是值,在前台页面中我们使用的是key.
            Velocity.Put("lResult", LResult);
            Velocity.Put("vResult", VResult);

           return Content(Velocity.Convert(content));

 

5.上面最后一句代码Velocity.Convert(content)调用NVelocityHelper.cs的Convert方法

       /// <summary>
       /// 返回解析后的html内容
       /// </summary>
       /// <param name="templateContent"></param>
       /// <returns></returns>
       public string Convert(string templateContent)
       {
           StringWriter writer = new StringWriter();
           velocity.Evaluate(context, writer, null, templateContent);

           return writer.GetStringBuilder().ToString();
       }

6.在前台的页面的html代码中引用在后台定义好的模板变量

#if($lResult)<span  style="float:left"><img  src="/ydt/cheng.png" /></span>#end

#if($vResult)<img src="/ydt/vip.png" οnlοad="fixPNG(this);"  />#end

转载于:https://www.cnblogs.com/jerry01/archive/2012/08/30/2664175.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值