【问题标题】:Methods/functions in t4 templates to return htmlt4 模板中返回 html 的方法/函数
【发布时间】: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


【解决方案1】:

我认为最简单的方法是为您的模板创建一个支持 DLL。在单元测试中测试所需的功能,然后以与此类似的方式引用您的支持 DLL...

<#@ assembly name="$(SolutionDir)[Project Name]\\bin\\Debug\\[Project Name].dll" #>

在本例中,[项目名称] 是您的支持项目的名称。引用后,在您的模板中将其实例化,如下所示...

var supportProj = new [Project Name]();

然后像使用任何其他类一样使用它。 此方法将您支持的 DLL 中的复杂逻辑抽象化,并使模板更易于消化。然后,支持的 DLL 可以在其中包含一个返回您需要的项目的方法。

【讨论】:

  • 啊,我目前正在通过创建一个自定义类来开发类似的解决方案,然后我可以将其作为参数传递给模板。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-30
相关资源
最近更新 更多