locked
is there a best practice to manage and maitain lots of T4 templates? RRS feed

  • General discussion

  • Hi, I wonder if there is such a thing for T4 templates.

     

    We have a lot of T4 and use them generate applications. The overwhelming part is: we use the same T4 to handle different pattern.

     

    For example, when generating a Silverlight MVVM application, we have View.xaml.t4, ViewModel.cs.t4, and Model.cs.t4.But a view could have a different pattern, such as it's a detail editing view or search view. Different pattern's MVVM could have similar parts, but some are different.

     

    Therefore, in those T4 files, we have lots of code in everywhere such as:

        if (pattern == PatternType.SimpleSearch)

               // generate this

        else if (pattern == PatternType.DetailEdit)

              // generate that

        else // more patterns

     

    this works well at the beginning, but after a long period and our code generation project grows, things are getting more and more complicated.

    1) we have many patterns, in one single t4, we have a few different blocks of pattern condition check;

    2) sometimes we generate different method signatures, then the caller (another T4) needs to update as well; so we need to be very careful to keep track all of them.

    3) duplicate code in a T4, because sometimes we have "if patternA, do 1,2,3; else if patternB, do 2,4,5", some cases are difficult to use common functions, so we have to generate duplicate code.

     

    anyway, not sure if that's clear.

    I just feel it got to have some better way to handle these situations

     

    Wednesday, January 19, 2011 6:10 PM

All replies

  • Hi Sowen,

    T4 include files combined with class feature blocks can help here.

    If you move your common code into a method that does the generation, then you can build up a library of such methods that can be included.

     

    For example, with your snippet in a file called PatternGenerator.t4

     

    <#+
    public void GeneratePattern(PatternType pattern)
    {
        if (pattern == PatternType.SimpleSearch)
    {
    #>
               // generate this
    <#+
    }
    else if (pattern == PatternType.DetailEdit)
    {
    #>
            // generate that
    <#+
    }
    else
    {
    #>
            // more patterns
    <#+
    }
    #>

    You can then call this from your main template by including the file and calling the method

    <#@ include file="Patterngenerator.t4" #>

     

    <# GeneratePattern(somePatternType); #>


    Gareth Jones - Developer Architect - T4, UML Designer Extensibility [MSFT]
    Tuesday, October 18, 2011 7:31 PM