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>

 

转载于:https://www.cnblogs.com/dandandeyoushangnan/p/4522888.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值