开发者

Can Conditional compilation symbols be used within T4 templates

开发者 https://www.devze.com 2023-04-06 02:07 出处:网络
I have a T4 template that is used with the TextTemplatingFilePreprocessor to generate a 开发者_开发问答class that I can then use to generate the output of the template.

I have a T4 template that is used with the TextTemplatingFilePreprocessor to generate a 开发者_开发问答class that I can then use to generate the output of the template.

At the start of the T4 template I import several namespaces. E.g.

<#@ import namespace="Company.ProductX.Widgets" #>
<#@ import namespace="Company.ProductX.Services" #>
//...

I'd like to use Preprocessor Directives to switch out these imports with another set of namespaces (which provide the same interfaces but differing functionality to ProductX). E.g.

<#
#if(ProductX)
{
#>
    <#@ import namespace="Company.ProductX.Widgets" #>
    <#@ import namespace="Company.ProductX.Services" #>
    //...
<#
}
#endif
#>
<#
#if(ProductY)
{
#>
    <#@ import namespace="Company.ProductY.Widgets" #>
    <#@ import namespace="Company.ProductY.Services" #>
    //...
<#
}
#endif
#>

With the above example the imports seem to create the corresponding using statements in the class regardless of the preprocessor directive. E.g.

using Company.ProductX.Widgets
using Company.ProductX.Services
using Company.ProductY.Widgets
using Company.ProductY.Services

Is there another way to use Preprocessors in T4 templates to affect the template itself rather than just the template output?


In your example the preprocessor directive is injected into the generated output. What you could potentially do is having a ProductX.tt file that imports the correct namespace and uses <#@ include #> to include the template code.

Something like this (ProductX.tt):

<#@ import namespace="Company.ProductX.Widgets"  #>
<#@ import namespace="Company.ProductX.Services" #>

<#@ include file="TheTemplateCode.ttinclude"     #>

(ProductY.tt):

<#@ import namespace="Company.ProductY.Widgets"  #>
<#@ import namespace="Company.ProductY.Services" #>

<#@ include file="TheTemplateCode.ttinclude"     #>

I am not sure if this helps you but to be honest I am struggling a little bit with the use-case here.


New idea for an old question.

It might be possible to use a Custom T4 Text Template Directive Processor to pass through arbitrary code to the T4 output.

The custom directive processor would need to be registered on each machine to use it.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号