tags:

views:

39

answers:

1

Hi Everybody,

I have a funtion named IterateThroughChildren() and I want to write the code to emit the code from inside of that function.

Normally the code block is included inside <# #> and custom functions are included inside <#+ #>, we emit our code inside <#= #> block. What if I want to recursively execute the above mentioned function and based on some logic I want to emit the code i.e.

e.g

<#
//Code to get child and parent data
IterateThroughChildren(object child, object parent);
#>

<#+
void IterateThroughChildren(object c, object p)
{
if(c is abc)
{
if(p is def)
{
//emit some code here i.e WriteLine(SomeThing); ?????
foreach (var item in def.Item)
{
IterateThroughChildren(item, def);
}

}
}

. . .

//and so on

}

#>

A: 

When you use the class feature blocks in T4, i.e. <#+ #>, then that code becomes part of the underlying class that generates the template's output file. In Visual Studio 2008, that underlying class derives from the abstract class Microsoft.VisualStudio.TextTemplating.TextTransformation.

Thus, you can write directly to the output stream by using the inherited Write() or WriteLine() methods. For example, in your code:

    <#
    //Code to get child and parent data
    IterateThroughChildren(object child, object parent);
    #>

    <#+
    void IterateThroughChildren(object c, object p)
    {
    if(c is abc)
    {
    if(p is def)
    {
    //emit some code here i.e WriteLine(SomeThing); ?????
    this.WriteLine(SomeThing); // writes SomeThing to the output file
    foreach (var item in def.Item)
    {
    IterateThroughChildren(item, def);
    }

    }
    }

. . .

//and so on

}

#>

where this.WriteLine(SomeThing) is the only thing I added.

Chris Melinn