T4模板使用include引入外部代码文件缩进异常如何解决
T4模板引入外部代码片段自动补全缩进解决方案
- 方案原理:弃用原生的
<#@ include #>指令,自定义辅助方法读取外部代码片段文件,逐行添加指定层级的缩进后再输出,无需手动修改外部片段文件的内容,灵活适配不同嵌套层级的缩进需求。
完整实现步骤
- 首先在模板顶部添加IO命名空间导入,你已开启
hostspecific="true"配置,可以直接用Host解析相对路径的片段文件:
<#@ import namespace="System.IO" #>
- 在模板末尾添加通用缩进引入的辅助方法:
<#+ /// <summary> /// 引入外部代码片段并自动添加缩进 /// </summary> /// <param name="filePath">片段文件路径,支持和模板文件的相对路径</param> /// <param name="indentLevel">缩进层级,默认1级对应4个空格</param> /// <param name="indentChar">缩进所用字符,默认空格,可改为'\t'使用Tab缩进</param> /// <param name="indentPerLevel">每级缩进的字符数量</param> void IncludeWithIndent(string filePath, int indentLevel = 0, char indentChar = ' ', int indentPerLevel = 4) { string fullPath = Host.ResolvePath(filePath); if (!File.Exists(fullPath)) { throw new FileNotFoundException("代码片段文件不存在", filePath); } string[] lines = File.ReadAllLines(fullPath); string indentStr = new string(indentChar, indentLevel * indentPerLevel); foreach (string line in lines) { // 空行也保留对应缩进,不需要可额外添加非空判断过滤 WriteLine(indentStr + line); } } #>
- 替换原有include指令:
将原来的引入代码
<#@ include file="Snippet.txt" #>
替换为以下代码,按照当前类内部的缩进需求设置indentLevel=1即可:
<# IncludeWithIndent("Snippet.txt", indentLevel: 1); #>
最终生成效果
修改后生成的代码会自动对齐层级:
namespace MyNamespace { public partial class MyClass { public void Function() { } } }
内容的提问来源于stack exchange,提问作者Anton Curmanschii
相关产品推荐
相关产品推荐

