#end
6.标签嵌套:
#foreach ($element in $list)
--外部循环--
$velocityCount:This is $element.
--内部循环--
#foreach ($element in $list)
$velocityCount:This is $element.
#end
--内部循环--
--外部循环--
#end
7.调用自定义对象方法:
#foreach( $s in $students )
$s.SayHello();
#end
using System.IO;
using NVelocity.App;
using NVelocity.Context;
using NVelocity.Runtime;
namespace NVelocity
{
///
/// NVelocity模板工具类 VelocityHelper
///
public class VelocityHelper
{
private IContext _context;
private VelocityEngine _velocity;
private string _templateName;
///
/// 构造函数
///
/// 模板文件夹路径
/// 模板文件名
public VelocityHelper(string templatDir, string templateName)
{
Init(templatDir);
_templateName = templateName;
}
///
/// 无参数构造函数
///
public VelocityHelper()
{
}
///
/// 设置模板文件夹
///
///
public void SetTemplateDirPath(string templatDir)
{
Init(templatDir);
}
///
/// 设置模板文件
///
///
public void SetTemplateFileName(string templateName)
{
_templateName = templateName;
}
///
/// 初始化NVelocity模块
///
/// 模板文件夹路径
public void Init(string templatDir)
{
//创建VelocityEngine实例对象并设置初始化VelocityEngine
_velocity = new VelocityEngine();
_velocity.SetProperty(RuntimeConstants_Fields.RESOURCE_LOADER, "file");
_velocity.SetProperty(RuntimeConstants_Fields.FILE_RESOURCE_LOADER_PATH, templatDir);
_velocity.SetProperty(RuntimeConstants_Fields.INPUT_ENCODING, "utf-8");
_velocity.SetProperty(RuntimeConstants_Fields.OUTPUT_ENCODING, "utf-8");
_velocity.Init();
//为模板变量赋值
_context = new VelocityContext();
}
///
/// 给模板变量赋值
///
/// 模板变量
/// 模板变量值
public void Put(string key, object value)
{
if (_context == null)
{
_context = new VelocityContext();
}
_context.Put(key, value);
}
///
/// 渲染模板
///
public string Render()
{
if (!string.IsNullOrEmpty(_templateName))
{
//从文件中读取模板
Template template = _velocity.GetTemplate(_templateName);
//合并模板
var writer = new StringWriter();
template.Merge(_context, writer);
return writer.GetStringBuilder().ToString();
}
return "未指定模板文件!";
}
}
}
完整Demo下载:
http://download.csdn.net/detail/a497785609/5405089
相关资料: