Can Conditional compilation symbols be used within T4 templates
Asked Answered
J

2

7

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?

Jacquelynejacquelynn answered 21/9, 2011 at 1:14 Comment(0)
F
5

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.

Fleabitten answered 21/9, 2011 at 20:37 Comment(2)
We use such 'header' templates to do this and find it works quite well. There isn't a way to insert conditionals around directives that's built in to the product.Orellana
Thanks for the answer. This sounds like a good work around. Once I've got it working I'll mark it as the solution.Jacquelynejacquelynn
J
0

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.

Jacquelynejacquelynn answered 19/10, 2015 at 21:30 Comment(1)
You could write a custom directive processor that was essentially a custom include directive, yes. It's a lot of work compared to the header template approach though.Orellana

© 2022 - 2024 — McMap. All rights reserved.