Bhav
Bhav

Reputation: 2195

Methods/functions in t4 templates to return html

I've got a large t4 text template to generate html.

t4 template:

<#@ 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>

Is it possible to create methods/functions in t4 templates to return large quantity of texts e.g. html tables/rows to be used within the t4 template?

I know I can add 'simple' methods to calculate and return 'simple' values e.g.

<#+
    public string GetReturnDate(string days)
    {
        var d = Convert.ToDouble(days);

        var returnDate = DateTime.Now.AddDays(d).ToString("ddd dd-MMM-yy");

        return returnDate.ToUpper();
    }
#>

The above method would return a date in string format.

However, in my t4 template example, I want to create a method/function to return multi-line html code so that I can reuse it in multiple places:

<# foreach (TransactionItem t in transaction) { #>
    <div>
    <p><#= t.Item #></p>
    <p><#= t.Price #></p>
    </div>
<# } #>

Upvotes: 2

Views: 1225

Answers (1)

Thundter
Thundter

Reputation: 580

I think the simplest way to do that is to create a supporting DLL for your template. Test the required functionality in unit tests and then refer to your supporting DLL in a similair way to this...

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

In this example [Project Name] is the name of your supporting project. Once referenced, instantiate it in your template something like this ...

var supportProj = new [Project Name]();

Then use it like any other class. This method abstracts the complicated logic in your supporting DLL and makes the template easier to digest. The supporting DLL can then have a method in it that returns the items you need.

Upvotes: 2

Related Questions