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.
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.
Structuring your T4 script like this might help, I have been using similar approaches in my projects successfully: -
<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ output extension=".cs" #>
<#
var Context = new ScriptContext();
Context.SomeFunction();
#>
// This file is generated by Build/Info.tt, do not modify!
void SomeFunction() {
public void GeneratedCode() {
int value = <#=Context.ValueForThisFile#>;
}
}
<#+
public class ScriptContext {
public int ValueForThisFile = 35;
public void SomeFunction()
{
ValueForThisFile = 42;
}
}
#>
Its possible to share variable accross functions in T4 template, Try this,
<#@ template debug="true" hostSpecific="true" #>
<#@ output extension=".cs" #>
<#@ import namespace="System.Collections.Generic" #>
<#
InitGlobalVariable();
AddNames();
ShowNames();
#>
<#+
//T4 Shared variables
List<string> names;
#>
<#+
private void InitGlobalVariable()
{
names = new List<string>();
}
private void AddNames()
{
names.Add("Mickey");
names.Add("Arthur");
}
private void ShowNames()
{
foreach(var name in names)
{
#>
<#= name #>
<#+
}
}
#>
Declare your variable inside <#+ ... #> and then initialize inside <# ... #>
来源:https://stackoverflow.com/questions/25773561/can-you-use-global-variables-inside-a-t4-template