使用DotLiquid的include标签时出现非法模板路径错误(C#)
DotLiquid include标签报错“Illegal template path”的解决方法
问题场景
使用DotLiquid NuGet包在C#中解析Liquid模板时,调用{% include 'function' %}引入子模板触发错误,报错路径实际有效且对应_function.liquid文件存在:
Liquid error: Error - Illegal template path 'D:\Include Trial1\DotLiquidTest\wwwroot\template_function.liquid'
相关代码
C#初始化代码:
string liquidTemplateContent = System.IO.File.ReadAllText("wwwroot/template/example.liquid"); LocalFileSystem fileSys = new DotLiquid.FileSystems.LocalFileSystem("wwwroot\template"); Template.FileSystem = fileSys; Template template = Template.Parse(liquidTemplateContent);
Liquid模板(example.liquid):
<p> Email: {{ employee.email }} </p> <p> Phone: {{ employee.phone }} </p> <p>Addresses:</p> <div> {% include 'function' -%} </div>
问题原因
- C#字符串路径转义错误:原代码中
"wwwroot\template"里的\t是C#转义字符(制表符),实际传递给LocalFileSystem的路径被解析为wwwroot+制表符+emplate,而非预期的wwwroot\template,导致DotLiquid拼接子模板路径时出现异常。 - LocalFileSystem安全验证:DotLiquid默认的LocalFileSystem会严格验证模板路径是否在指定根目录下,根路径解析错误会直接导致子路径被判定为非法。
解决方案
1. 修正路径转义
将C#中的路径字符串改为以下两种正确写法之一,确保路径被正确解析:
// 方式1:使用双反斜杠转义 LocalFileSystem fileSys = new DotLiquid.FileSystems.LocalFileSystem("wwwroot\\template"); // 方式2:使用逐字字符串(@前缀,避免转义) LocalFileSystem fileSys = new DotLiquid.FileSystems.LocalFileSystem(@"wwwroot\template");
2. 自定义FileSystem(可选,应对严格验证场景)
如果默认LocalFileSystem的验证逻辑仍导致问题,可以自定义FileSystem继承IFileSystem,按需调整路径处理逻辑:
public class CustomFileSystem : DotLiquid.FileSystems.IFileSystem { private readonly string _rootFullPath; public CustomFileSystem(string rootPath) { _rootFullPath = Path.GetFullPath(rootPath); } public string ReadTemplateFile(Context context, string templateName) { // 拼接子模板完整路径(根据实际文件命名规则调整) var templatePath = Path.Combine(_rootFullPath, $"_{templateName}.liquid"); // 可选:保留根目录验证,防止路径遍历 if (!templatePath.StartsWith(_rootFullPath, StringComparison.OrdinalIgnoreCase)) throw new InvalidOperationException("非法模板路径"); return File.ReadAllText(templatePath); } }
替换原代码中的FileSystem初始化:
CustomFileSystem fileSys = new CustomFileSystem(@"wwwroot\template"); Template.FileSystem = fileSys;
内容的提问来源于stack exchange,提问作者Kedar Ghadge
相关产品推荐
相关产品推荐

