T4 vs Razor – what’s the skinny?
A few customers have been asking folks on both teams some questions around this, such as the following.
- Why do you have two engines?
- When should I use each of these two engines?
- When can I expect <feature X> from one engine to appear in the other one?
So the T4 and Razor teams got ourselves together in a room and came up with a common way to express how we think about some of these things. Here’s what we came up with:
|Design-time hosting||Visual Studio & co-installed tools||Anywhere|
|Runtime options||Preprocessed templates||Rehost Razor engine|
|Recommended for generating which file types?||Not markup||Markup|
|Optimized for||Generating arbitrary code assets||Efficient HTML generation|
|Productivity aids||Class feature blocks (virtual methods) Include directive (template fragment libraries)||Helpers (static standalone code) Sections (overridable content)|
|Extensibility||Custom directives VS Service Custom host||Customize or replace most elements of the stack Custom host|
|Editing||3rd party editors||VS built-in (HTML output optimized)|
|Core control languages||C#/VB||C#/VB|
In short, we have two engines ‘cos they’re optimized for different use cases.
- Razor uses its implicit knowledge of the type of output it’s generating to allow it to disambiguate control code from output markup and so use a much terser and more pleasing syntax.
- T4 is designed to generate arbitrary text output, which often means that the output you’re generating and the control language will be the same; consequently, it has to use more explicit demarcation syntax.
We’ll keep adding individual syntax and features that make sense for those separate use cases, but we’ll try and avoid being different at a conceptual level just for the sake of it.