Nvelocity对象索引和#foreach举例

首先写一个login.ashx的一般处理程序,引用Nvelocity动态类库,在写一个数组一个list集合和一个字典集合.

放入到参数中,并且指定模版的网页。

public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/html";
            Dictionary<string, string> dict = new Dictionary<string, string>();
            dict["tom"] = "斯坦福";
            dict ["jim"]="家里蹲";
            dict["yxk"] = "北大";

            string[] strs = new string[] { "路id恶化","万恶","山鸡"};
            List<Person> list = new List<Person>();
            list.Add(new Person { Age =30,Name ="杨中科"});
            list.Add(new Person { Age =10,Name ="扬中"});
            list.Add(new Person { Age =12,Name =""});

            VelocityEngine vltEngine = new VelocityEngine();//实例化一个velocity模版引擎
            vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file");
            vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, System.Web.Hosting.HostingEnvironment.MapPath("~/templates"));//模板文件所在的文件夹
            vltEngine.Init();

            VelocityContext vltContext = new VelocityContext();
            vltContext.Put("ps",dict );//设置参数,在模板中可以通过$data来引用
            //把person对象作为传入p
            vltContext.Put("mingrens",strs );
            vltContext.Put("persons",list );



            Template vltTemplate = vltEngine.GetTemplate("test3.htm");
            System.IO.StringWriter vltWriter = new System.IO.StringWriter();
            vltTemplate.Merge(vltContext, vltWriter);

            string html = vltWriter.GetStringBuilder().ToString();//得到html这个模板
            context.Response.Write(html);




        }

写一个模板网页,在一个无序的列表中,#标记是nvelocity语法。

<body>
    1:
    <!-- $ps.tom<br />-->
    <ul>
        #foreach($mr in $mingrens)
        <li>$mr</li>
        #end
    </ul>

    <ul>
    #foreach($p in $persons)
    <li>$p.Name,$p.Age</li>
    #end
    </ul>
</body>
</html>

 

posted @ 2015-05-22 17:27  淡淡的忧伤IT男  阅读(1383)  评论(1编辑  收藏  举报