当然。
完整的 nVelocity 模板:
<div>
Bet summary:
<ul>
#foreach( $bet in $bets )
<li>
$bet.Date $bet.Race
#if($bet.Amount > 10)
<strong>$bet.Amount.ToString("c")</strong>
#else
$bet.Amount.ToString("c")
#end
</li>
#end
</ul>
</div>
投注类:
public class Bet
{
public Bet(decimal amount, string race, DateTime date)
{
Amount = amount;
Race = race;
Date = date;
}
public decimal Amount { get; set; }
public string Race { get; set; }
public DateTime Date { get; set; }
}
程序:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Commons.Collections;
using NVelocity.App;
using NVelocity;
using NVelocity.Runtime;
namespace nVelocityTest
{
public class Program
{
private static void Init()
{
var props = new ExtendedProperties();
props.AddProperty(RuntimeConstants_Fields.FILE_RESOURCE_LOADER_PATH, @"C:\dev\RnD\nVelocity\nVelocityTest\nVelocityTest\EmailTemplates");
Velocity.Init(props);
}
static void Main()
{
Init();
ICollection<Bet> bet = new Collection<Bet> { new Bet(10, "Banana Race", DateTime.Now), new Bet(15, "Potatoe Race", DateTime.Now) };
GenerateBetSummaryEmail(bet);
}
private static void GenerateBetSummaryEmail(ICollection<Bet> bets)
{
var context = new VelocityContext();
context.Put("bets", bets);
var writer = new System.IO.StringWriter();
try
{
Velocity.MergeTemplate("BetConfirmationEmailTemplate.vm", context, writer);
}
catch (Exception e)
{
Console.WriteLine("Problem merging template : " + e);
}
var outputTest = writer.GetStringBuilder().ToString();
}
}
}
预期输出测试:
以下是您的投注摘要:
- 25/03/2010 9:21:15 AM 香蕉赛 $10.00
-
25/03/2010 9:21:15 AM 土豆赛
$15.00
实际输出测试:
以下是您的投注摘要:
- 25/03/2010 9:21:15 AM 香蕉赛 $10.00
-
25/03/2010 9:21:15 AM 土豆赛 $15.00
如前所述,nVelocity 模板中的比较 #if($bet.Amount > 10) 失败,即使在第二个 bet 对象中,bet.Amount 的值为 15。如果将 Amount 更改为 int 类型,则比较按预期工作。