Templating: template content containing preprocessor directives

Created on 3 Apr 2018  路  1Comment  路  Source: dotnet/templating

we have a use case to generate content that contains pre-processor directive code (to be switched on or off). This is used for local dev/debugging purposes. The full use case is to allow for what would otherwise be Service Fabric deployed WebAPI to be hosted as standalone .net core app - outside of SF. This simplifies local developer experience and also speeds things up.

example of such code would be

if DEBUGNOFABRIC

             var host = WebHost.CreateDefaultBuilder()
                .UseStartup<Startup>()                       
                .Build();
            host.Run();

else

.... standalone ServiceRuntime call of SF

endif

however since pre-processor directives are used by (correct me if I am wrong) by the templating engine itself, this code is being filtered out (since the symbol evaluates to false by default)

I do not see any option right now to "escape" such pre-processor directive so that it is ignored by the templating engine.

for now I commented out the pre-processor directive in the template source but it means the end user must re-enable it to avail of this facility

Most helpful comment

Hi @VaclavK, the way to escape these directives is described in https://github.com/dotnet/templating/issues/1354#issuecomment-346186262. Essentially, you'll want to surround the blocks that you want the literal preprocessors left in with a directive, like this

//-:cnd:noEmit
#if STUFF
...
#endif
//+:cnd:noEmit

To unpack this a little, this is a use of "processing flags". Processing flags are specified as either two or three parts and are structured as //{+/-}:{flag name}[:{noEmit}]. The - indicates that we're turning a flag off (+ indicates turning it on), cnd is the "condition" processing flag, and noEmit indicates that the flag directive itself shouldn't be left in the output (useful when the template output is a template), if not specified, the default is to emit the flags directive.

>All comments

Hi @VaclavK, the way to escape these directives is described in https://github.com/dotnet/templating/issues/1354#issuecomment-346186262. Essentially, you'll want to surround the blocks that you want the literal preprocessors left in with a directive, like this

//-:cnd:noEmit
#if STUFF
...
#endif
//+:cnd:noEmit

To unpack this a little, this is a use of "processing flags". Processing flags are specified as either two or three parts and are structured as //{+/-}:{flag name}[:{noEmit}]. The - indicates that we're turning a flag off (+ indicates turning it on), cnd is the "condition" processing flag, and noEmit indicates that the flag directive itself shouldn't be left in the output (useful when the template output is a template), if not specified, the default is to emit the flags directive.

Was this page helpful?
0 / 5 - 0 ratings