Spa*_*man 3 c# razor razor-2 razorengine
我正在使用最新版的剃须刀. https://github.com/Antaris/RazorEngine
我想将它附加到一些cshtml并调试它.
自述文件陈述如下
调试
您可能想要启用的一件事是调试功能:
Run Code Online (Sandbox Code Playgroud)config.Debug = true;当Debug为true时,您可以直接调试生成的代码.RazorEngine还支持直接调试模板文件(通常是.cshtml文件).正如您在上面的代码中看到的那样,没有要调试的文件.要为RazorEngine提供必要的信息,您需要告诉它可以找到文件的位置:
Run Code Online (Sandbox Code Playgroud)string template = "Hello @Model.Name, welcome to RazorEngine!"; string templateFile = "C:/mytemplate.cshtml" var result = Engine.Razor.RunCompile(new LoadedTemplateSource(template, templateFile), "templateKey", null, new {在我的代码中,我设置了以下内容
Run Code Online (Sandbox Code Playgroud)var config = new TemplateServiceConfiguration(); // .. configure your instance config.Debug = true; var service = RazorEngineService.Create(config); Engine.Razor = service; //string template = "Hello @Model.Name, welcome to RazorEngine!"; string templateFile = "C:/mytemplate.cshtml"; var template = new LoadedTemplateSource("", templateFile); var result = Engine.Razor.RunCompile(template, this.Name, null, model);
现在我在该路径中创建了一个cshtml文件,其中包含以下内容.
@{
var a = 1;
a = a + a;
@a
}
<div>
hi
</div>
Run Code Online (Sandbox Code Playgroud)
但我得到一个空字符串:(当我进入它时它只是跨过:( :(.
我不知道我做错了什么人有任何想法.
答案代码
string templateFile = "C:/mytemplate.cshtml";
StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader(templateFile))
{
String line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
sb.AppendLine(line);
}
}
string allines = sb.ToString();
var template = new LoadedTemplateSource(allines, templateFile);
var result = Engine.Razor.RunCompile(template, this.Name, null, model);
Run Code Online (Sandbox Code Playgroud)
该LoadedTemplateSource代表模板源代码,你给""的源代码,因此你的模板是空的.
第一个参数LoadedTemplateSource需要是模板的源代码,第二个参数是文件的路径,仅用于调试目的.
如果您需要延迟加载或自定义加载器策略,您可以实现自定义,ITemplateSource或者ITemplateManager在内存中有源可用时也会改进一些错误消息.
matthid,RazorEngine贡献者