using System; using System.IO; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using NVelocity; using NVelocity.App; using NVelocity.Context; using NVelocity.Runtime; using NVelocity.Tool; using NVelocity.Util; using Commons; using Commons.Collections; //http://www.cnblogs.com/McJeremy/archive/2008/06/25/1229848.html namespace WebApplication1 { public partial class _Default : Page { protected void Page_Load(object sender, EventArgs e) { VelocityEngine velocity = new VelocityEngine(); //也可以使用带参构造函数直接实例。 ExtendedProperties props = new ExtendedProperties(); props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, Server.MapPath("Tmp")); props.AddProperty(RuntimeConstants.INPUT_ENCODING, "gb2312"); props.AddProperty(RuntimeConstants.OUTPUT_ENCODING, "gb2312"); velocity.Init(props); Template template = velocity.GetTemplate(@"/demo.tmp"); VelocityContext context = new VelocityContext(); context.Put("from", "Beijin"); context.Put("to", "Xiamen"); Model m = new Model() { Name = "QiangZhe", Age = 23, Body = new Body() { Weight = 60, Height = 163 } }; context.Put("Model", m); StringWriter writer = new StringWriter(); template.Merge(context, writer); Response.Write(writer.ToString()); } } public class Model { public string Name { get; set; } public int Age { get; set; } public Body Body{get;set;} } public class Body { public int Height { get; set; } public int Weight { get; set; } } }
Demo.tmp
#include( "header.txt" ) <br/> Count down. #set( $count = 8 ) #parse( "child.tmp" ) All done with child.tmp! <br/> #foreach( $foo in [13..-6] ) #if( $foo < 10 ) <strong>Go North</strong> #elseif( $foo == 10 ) <strong>Go East</strong> #elseif( $bar == 6 ) <strong>Go South</strong> #else <strong>Go West</strong> #end #end <br/> $Model.Name $Model.Age $Model.Body.Height #set($List = ["man","woman","middle","none"]) <p> ForEach </p> #foreach($Item in $List) #odd <p>$velocityCount odd $Item</p> #even <p>$velocityCount even $Item</p> #end #macro( tablerows $color $somelist ) #foreach( $something in $somelist ) <tr><td bgcolor=$color>$something</td></tr> #end #end #set( $parts = ["volva","stipe","annulus","gills","pileus"] ) #set( $cellbgcol = "#CC00FF" ) <table> #tablerows( $cellbgcol $parts ) </table> $from <br/> #set( $size = "Big" ) #set( $name = "Ben" ) #set($clock = "${size}Tall$name" ) $clock Stop #stop $to
时间: 2024-10-03 21:53:17