Comments in T4 Templates

CommentsT4

Comments Problem Overview


This seems like such a basic question, but I haven't been able to find an MSDN article or StackOverflow question that answers it: is it possible to make line comments or block comments in T4 templates? I'm not looking to generate code with comments (that's easy and straightforward) but rather comment out blocks of my T4 markup. Is that possible?

Comments Solutions


Solution 1 - Comments

To include comments as part of control code, they need to be inside a code block of some sort, for example

<# // Hello this is a comment #>

or

<#+ // Hello this is a comment in a class feature block #>

Sometimes you need to push the close tag to the next line if you're sensitive to extra newlines in the output.

If you want to comment out whole blocks of markup, there isn't a straightforward solution unfortunately, and the result gets rather ugly.

You can do it by escaping the tags that you'd like to comment, like so:

\<# my control code \#>

and then placing that inside a comment in another block like so:

<# // \<# my control code \#> #>

Solution 2 - Comments

The best way to add block comment is to use #if and #endif

<#
   #if false
   foreach(var typeName in typeNames)
   { 
       var className = typeName + "Adapter";
#>
    // ...
<#  
    }
    #endif
#>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionamossView Question on Stackoverflow
Solution 1 - CommentsGarethJView Answer on Stackoverflow
Solution 2 - CommentsengineforceView Answer on Stackoverflow