Get Visual Studio to run a T4 Template on every build

后端 未结 22 2416
余生分开走
余生分开走 2020-11-22 08:29

How do I get a T4 template to generate its output on every build? As it is now, it only regenerates it when I make a change to the template.

I have found other ques

22条回答
  •  渐次进展
    2020-11-22 09:17

    Expanding on Seth Reno and JoelFan's answers, I came up with this. With this solution don't need to remember to modify the pre-build event every time you add a new .tt file to the project.

    Implementation Procedure

    • Create a batch file named transform_all.bat (see below)
    • Create a pre-build event transform_all.bat "$(ProjectDir)" $(ProjectExt) for each project with a .tt you want to build

    transform_all.bat

    @echo off
    SETLOCAL ENABLEDELAYEDEXPANSION
    
    :: set the correct path to the the app
    if not defined ProgramFiles(x86). (
      echo 32-bit OS detected
      set ttPath=%CommonProgramFiles%\Microsoft Shared\TextTemplating\1.2\
    ) else (
      echo 64-bit OS detected
      set ttPath=%CommonProgramFiles(x86)%\Microsoft Shared\TextTemplating\1.2\
    )
    
    :: set the working dir (default to current dir)
    if not (%1)==() pushd %~dp1
    
    :: set the file extension (default to vb)
    set ext=%2
    if /i %ext:~1%==vbproj (
      set ext=vb
    ) else if /i %ext:~1%==csproj (
      set ext=cs
    ) else if /i [%ext%]==[] (
      set ext=vb
    )
    
    :: create a list of all the T4 templates in the working dir
    echo Running TextTransform from %cd%
    dir *.tt /b /s | findstr /vi obj > t4list.txt
    
    :: transform all the templates
    set blank=.
    for /f "delims=" %%d in (t4list.txt) do (
      set file_name=%%d
      set file_name=!file_name:~0,-3!.%ext%
      echo:  \--^> !!file_name:%cd%=%blank%!
      "%ttPath%TextTransform.exe" -out "!file_name!" "%%d"
    )
    
    :: delete T4 list and return to previous directory
    del t4list.txt
    popd
    
    echo T4 transformation complete
    


    NOTES

    1. The text transformation assumes the code in the T4 template is the same language as your project type. If this case does not apply to you, then you will have to replace the $(ProjectExt) argument with the extension of the files you want the code generate.

    2. .TT files must be in the project directory else they won't build. You can build TT files outside the project directory by specifying a different path as the first argument (i.e. replace "$(ProjectDir)" with the path containing the TT files.)

    3. Remember also to set the correct path to the transform_all.bat batch file.
      For example, I placed it in my solution directory so the pre-build event was as follows "$(SolutionDir)transform_all.bat" "$(ProjectDir)" $(ProjectExt)

提交回复
热议问题