您的位置:首页 > 编程语言

关于Nvelocity的主要语法和一些代码示例

2013-11-27 22:25 549 查看
context.Response.ContentType = "text/html";
VelocityEngine vltEngine = new VelocityEngine();
vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file");
vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, System.Web.Hosting.HostingEnvironment.MapPath("~/templates"));//模板文件所在的文件夹
vltEngine.Init();

//匿名类 把类的定义和对象的声明初使化放到一起
var news = new { Title = "ffff", Author = "AL", PostDate = "2013-11-8", Msg = "公布消息细节" };

VelocityContext vltContext = new VelocityContext();
vltContext.Put("people", news);//设置参数,在模板中可以通过$data来引用

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

string html = vltWriter.GetStringBuilder().ToString();
context.Response.Write(html); //输出html代码


  下面是Html里的模板引擎的语法写法 和C#很相似

<!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>
#parse("head.htm")

$ps.tom

1:
<ul>
#foreach($mr in $MR)
<li>$mr</li>
#end
</ul>
2:
<ul>
#foreach($prs in $persons)
<li>$prs.Name 年龄是 $prs.Age</li>
#end
</ul>

#if($age>10)
大于10
#else
小于等于10
#end

3:
<ul>
#foreach($prs in $persons)
#if($prs.Age>20)
<li style="color:Red">$prs.Name的年龄是$prs.Age</li>
#else
<li style="color:Black">$prs.Name的年龄是$prs.Age</li>
#end
#end
</ul>
#parse("foot.htm")
</body>
</html>


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: