初识NVelocity

在修改部分错误时,好好的把之前的老项目看了下,由于开始做.net时直接上的mvc对webform不太了解,如果不用托拉拽还真不知道逻辑中的数据如何在页面上显示。花了点时间吧NVelocity看了下,这玩意还挺好用

  下面是简单的尝试:

    

 private List<string> list=new List<string>();
        protected void Page_Load(object sender, EventArgs e)
        {
            list.Add("111");
            list.Add("222");
            list.Add("333");
            list.Add("444");
            list.Add("555");
            list.Add("666");
            list.Add("777");
            list.Add("888");
            load_data(list);
        }
        void load_data(List<string> list)
        {
             VelocityEngine Engine=new VelocityEngine();
             ExtendedProperties props = new ExtendedProperties();

             props.AddProperty(RuntimeConstants.RESOURCE_LOADER,"file");
             props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH,Server.MapPath("~/"));

             Engine.Init(props);
             
             VelocityContext context=new VelocityContext();//页面所需的数据就保存于此
            context.Put("blogs", list);
            Template temp = Engine.GetTemplate("HTMLPage1.htm");
            System.IO.StringWriter sw=new StringWriter();
            temp.Merge(context,sw);

            Response.Write(sw.ToString());
        }

 页面代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
#foreach($info in $blogs)

     ${info}
  
#end
</body>
</html>

这时结果就会在页面输出了

原文地址:https://www.cnblogs.com/steben/p/3106279.html