Search code examples
asp.net-mvcrazorrazorengine

Razor engine if else statement


Do I really have to mark each line with "@:" when I am evaluating a template with Razor Engine and just want to print the whole block contained inside of If statement:

@if(Model.Labels)
{
    @:arcs.append("text")
    @:.attr("transform", function (d) {
        @:var c = arc.centroid(d),
            @:x = c[0],
            @:y = c[1],
            @:// pythagorean theorem for hypotenuse
            @:h = Math.sqrt(x * x + y * y);
        @:return "translate(" + (x / h * labelr) + ',' +
           @:(y / h * labelr) + ")";
    @:})
    @:.attr("dy", ".35em")
    @:.attr("text-anchor", function (d) {
        @:// are we past the center?
        @:return (d.endAngle + d.startAngle) / 2 > Math.PI ?
            @:"end" : "start";
    @:})
    @:.text(function (d) { return d.data.name; });
}
else
{

}

Solution

  • You can check a great post about Razor syntax here: http://weblogs.asp.net/scottgu/asp-net-mvc-3-razor-s-and-lt-text-gt-syntax

    In short, the rule applied here is:

    You have a code block - your "if" - and inside of it, code is expected unless:

    1. You put an html tag inside. This way, content inside of "if" block will be treated as HTML.
    2. You use <text></text> tag. This way, content inside text tag will be rendered as you put it, without adding any tags or text around it, so for your javascript code it will render the code that you specified.
    3. Your text is preceded with @: lexeme, which tells razor that content after it should be treated as html/text.

    In short, changing your code to this one is what you need:

    @if(Model.Labels)
    {
        <text>
            arcs.append("text")
            .attr("transform", function (d) {
                var c = arc.centroid(d),
                        x = c[0],
                        y = c[1],
                        // pythagorean theorem for hypotenuse
                        h = Math.sqrt(x * x + y * y);
                return "translate(" + (x / h * labelr) + ',' +
                        (y / h * labelr) + ")";
                })
            .attr("dy", ".35em")
            .attr("text-anchor", function (d) {
                // are we past the center?
                return (d.endAngle + d.startAngle) / 2 > Math.PI ?
                        "end" : "start";
                })
            .text(function (d) { return d.data.name; });
        </text>
    }
    else
    {
    
    }