【问题标题】:RazorEngine: Does not parse variable that appears after a less than sign ("<")RazorEngine:不解析出现在小于号 ("<") 之后的变量
【发布时间】:2014-04-22 20:40:58
【问题描述】:

当 razor 模板有一个用括号括起来的变量时(例如,下面代码中的“(@Model.B)”),如果该变量前面有一个“

[Test]
public void TestWeirdLangleBracketError()
{
    var template = "(@Model.B)";
    var model = new Model { B = Guid.NewGuid().ToString() };
    var templateService =
        new TemplateService(new TemplateServiceConfiguration { EncodedStringFactory = new RawStringFactory() });

    //It is replaced here
    //Result of Try1: "(f9e0f220-0df8-4942-9d84-e403c622af96)"
    templateService.Compile(template, typeof(Model), "Try1");
    Assert.True(templateService.Run("Try1", model, null).Contains(model.B));
    //But not here
    //Result of Try2: " < (@Model.B)"
    templateService.Compile(" < " + template, typeof(Model), "Try2");
    Assert.False(templateService.Run("Try2", model, null).Contains(model.B));
}

public class Model
{
    public string B { get; set; }
}

【问题讨论】:

  • 有错误信息吗?
  • 代码编译和执行没有错误,尽管有意想不到的结果。

标签: c# razor razorengine


【解决方案1】:

Razor 严重依赖 符号来查找将用作 html 的标签。

要解决您的问题,您可以使用 xml 替换

&lt; (@Model.B) 

实际代码在答案中被替换查找小于为实际替换文本编码的符号 xml

或者这个

@("<") (@Model)

问题在于 Model.B 定义。

【讨论】:

  • 两者都应该在技术上工作。如果 @ 在括号之外,那么剃刀应该将括号作为表达式的一部分进行计算。如果它在内部,则不应将它们包含在表达式评估中并将它们作为原始文本输出,这就是结果字符串在括号中包含 GUID 的原因。
  • 编辑了我的答案以更符合您的问题
【解决方案2】:

您的代码行有错误。

templateService.Compile(" < " + template, typeof(Model), "Try2");

我没有引用@Model.B,所以它只会输出“

你需要像这样实际包含变量。

templateService.Compile(" < (@Model.B)" + template, typeof(Model), "Try2");

【讨论】:

  • var template = "(@Model.B)";所以@Model.B 在那里被引用。
猜你喜欢
  • 1970-01-01
  • 2016-05-19
  • 2013-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多