Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reusing method of T4 template in other T4 templates

Tags:

templates

t4

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)?

like image 307
Ari Avatar asked Nov 26 '25 02:11

Ari


2 Answers

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

<#@ include file="Included.tt" #>
like image 103
Matt Ward Avatar answered Nov 28 '25 16:11

Matt Ward


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 #>
like image 26
Dan Avatar answered Nov 28 '25 16:11

Dan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!