RazorEngine: does not parse the variable that appears after the less than sign ("<")

When the razor template has a variable enclosed in brackets (for example, “(B Model.B)” in the code below), the razor mechanism cannot compile and replace this variable if it is preceded by “<” and separated by a space or text. Is this intentional behavior? If the variable is not completed in brackets, then the template parses just fine.

[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; }
}
+4
source share
2 answers

The razor is heavily dependent on <> tags for finding tags to be used as html.

To solve your problem, you can use xml replacement for <

&lt; (@Model.B) 

, xml,

@("<") (@Model)

& ​​lt; Model.B.

+1

.

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

@Model.B, "<"

, .

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

Source: https://habr.com/ru/post/1537568/


All Articles