【发布时间】:2018-08-05 23:31:03
【问题描述】:
我有一个大的 t4 文本模板来生成 html。
t4 模板:
<#@ template language="C#" debug="true" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.Globalization" #>
<#@ parameter type="Transaction" name="transaction" #>
<#@ parameter type="System.Collections.Generic.Dictionary<string,string>" name="resources" #>
<html>
<p>test paragraph1 </p>
<# foreach (TransactionItem t in transaction) { #>
<p><#= t.Item #> <#= t.Price #></p>
<# } #>
<p>test paragraph2 </p>
<p>test paragraph3</p>
<p>
<#= this.GetClearanceReturnDate(14); #></p>
</html>
是否可以在 t4 模板中创建方法/函数以返回大量文本,例如要在 t4 模板中使用的 html 表/行?
我知道我可以添加“简单”方法来计算和返回“简单”值,例如
<#+
public string GetReturnDate(string days)
{
var d = Convert.ToDouble(days);
var returnDate = DateTime.Now.AddDays(d).ToString("ddd dd-MMM-yy");
return returnDate.ToUpper();
}
#>
上述方法将返回字符串格式的日期。
但是,在我的 t4 模板示例中,我想创建一个方法/函数来返回多行 html 代码,以便我可以在多个地方重用它:
<# foreach (TransactionItem t in transaction) { #>
<div>
<p><#= t.Item #></p>
<p><#= t.Price #></p>
</div>
<# } #>
【问题讨论】:
-
为什么不创建另一个模板来保存它?
-
在模型-视图-控制器和衍生架构中,将数据转换放在模型而不是视图中几乎总是更有用。
-
@CamiloTerevinto 我已经有多个模板,例如headerTemplate、bodyTemplate、footTemplate 和它们都输出数据。然后我将返回的值作为参数传递给 masterTemplate。我的问题是我想避免在 bodyTemplate 中重复代码。
-
@Gusdor 我同意。那是一个糟糕的例子。我的观点是可以为“简单”对象创建“简单”方法,但我希望能够返回更复杂的 html。
标签: c# html code-generation t4