locked
Dynamically call a T4 template from within another T4 template RRS feed

  • Question

  • I'm building a code generation tool. I will run T4 precompiled templates (code) to output the generated code. Within those templates I want to dynamically call other (helper) templates that output to the same file. By dynamically  I mean: data driven - I wont know what templates to call until runtime.

    Question is: is that possible and how will that work?

    Extra Info: The tool will be available in two versions: a standalone version that uses precompiled T4 template - because the T4 engine cannot be redistributed outside VS2010, and a VS2010 add in, that could use file based templates -the user could customize- and generate code from those directly.


    Marc Jacobi
    Monday, October 18, 2010 9:18 AM

Answers

  • The easy way to include one template in another is with the @include directive, but you can't use that dynamically.

    So instead, call one template from another.

    Template1:

     

    Blah Blah
    
    // Template2 is another precompiled text template:
    
    <# if (condition) 
      {
        this.Write((new Template2()).TransformText()); 
      } #>
    
    
    or:
    
    <# if (condition) { #>
    <#= (new Template2()).TransformText() #>
    <#  } #>
    
    
    Monday, October 18, 2010 11:49 PM

All replies

  • The easy way to include one template in another is with the @include directive, but you can't use that dynamically.

    So instead, call one template from another.

    Template1:

     

    Blah Blah
    
    // Template2 is another precompiled text template:
    
    <# if (condition) 
      {
        this.Write((new Template2()).TransformText()); 
      } #>
    
    
    or:
    
    <# if (condition) { #>
    <#= (new Template2()).TransformText() #>
    <#  } #>
    
    
    Monday, October 18, 2010 11:49 PM
  • Thanks Allen. Its so simple, I totally overlooked it ;-)

    But how would it work for non-precompiled templates?

     

    I want to give the users of the VS2010 addin an option to customize the template sources.

    Or should I build something that grabs the new templates sources, precompiles them and build an assembly on the fly that is dynamically/manually loaded into the app...? Unloading would be a pain/separate AppDomain/Marshaling.


    Marc Jacobi
    Tuesday, October 19, 2010 8:23 AM