Can you use global variables inside a t4 template?

t4

Solution

I don't think that is possible. When T4 parses your template it is actually generating a class. All the <# #> contents are injected into a single method on that class while all <#+ #> tags are added as methods to that class, allowing you to call them from the single method <# #> tags. So the scope of the "ValueForThisFile" variable is limited to that single method. For a simple example, this template:

<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ output extension=".cs" #>
<# 
     int ValueForThisFile = 35;

     SomeFunction();
#>

<#+
void SomeFunction() {
   return ValueForThisFile;
}
#>

Would Generate a class like this:

class T4Gen {

private void MainWork() {
    int ValueForThisFile = 35;
    this.SomeFunction();
}

private void SomeFunction{
    return ValueForThisFile;
}

}

The variable "ValueForThisFile" is only scoped to the MainWork function. The actual class T4 generates is much more complicated but as you see there would be no way to have a global variable in code like that.

Problem

How can I use global variables in a TT file? If I declare a variable in the header I get a compile error if I reference it in a function. ``` <#@ template debug="false" hostspecific="false" language="C#" #> <#@ output extension=".cs" #> <# int ValueForThisFile = 35; SomeFunction(); #> <#+ void SomeFunction() { #> public void GeneratedCode() { int value = <#=ValueForThisFile#>; } <#+ } #> ``` I know that I could pass it as an argument but there are hundreds of calls and it would be syntactically tighter if I could avoid that. If this were one file I could hard code the value but there are dozens of files that have different settings and common include files that generate the code.

Original source