Question

At the end of my T4 template file I have some functions defined:

<#+
    type Foo(...) { ... }
    type Bar(...) { ... }
    ...
#>

It works fine.

Now I'm creating other template. Is there any way to use functions declared in my first template file (maybe by using third file to store these functions)?

Was it helpful?

Solution

You can use the include directive to share code that is in another file.

<#@ include file="Included.tt" #>

OTHER TIPS

Matt answer is 100% correct... but I prefer to use a "Model" , sometimes in a different assembly , that way I can use the Template more like a view without the logic for code generation , with exception of very simple loops, (for,foreachs...etc). I thinks later on is way easier to read. maintain, reuse and troubleshoot. due to the model being written in plain c# , simplistic , and not tested example

 <#@ output extension=".generated.cs" #>
 <#@ assembly name="$(SolutionDir)Bin\Net45\GeneratorModel.dll" #>
 <#@ import namespace="System.Collections.Generic" #>
 <#@ import namespace="GeneratorModel" #>
 <#@ import namespace="Extensions" #>
 <# IEnumerable<Type> entities = GetCollection();
    const string nameSpace = GetNameSpace();
  #> //Autogenerated Stuff
  using System;
  using System.Collections.Generic;
  namespace <#=nameSpace#> 
  {
    public interface IEntity{}

    <# foreach (var entity in entities){#>  

    #region class

    public partial class <#=entity.Name#> : IEntity {
        <#foreach(var prop in entity.GetPublicProperties()){#>
          /* More stuff Here .. */              
        <#}#>
    }

    #endregion class    
    <#}#>                                       
   }<#// End OF NameSpace #>

First question: are you using 2012 or 2010? 2010 has a problem that there is no inclusion guards for T4. This means that if you make a reusable T4 helper-methods file, you have to be careful about including it over and over again and getting errors from referencing the same files. In trivial cases T4 is fine for this, but you'll run into problems if you start building large constructs in T4 using Sych's T4Toolbox or something.

<#@ include file="MyTools.Include.tt" #>

Also, you should consider that you really have two types of Templates - "root" templates that are intended to be generated directly, and "support" templates that are intended to be included - it's good to come up with a convention to differentiate these - I use a ".Include.tt" filename for that, but others will have their own approach. You'll also want to clear the "Custom Tool" attribute from your include files, so that you can freely use the "Transform All" command without wasting time on the garbage templates.

In the extreme case, you can compile your own assemblies to be used by T4. This allows you fast transformations rather than waiting to dynamically compile your reusable stuff... but this has its own problems.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top