I'm working with razor templates, I have two if's inside a foreach.

I've attached the simple code. But when I use Template Builder razor doesn't interpret the second if (it's like a text for Razor). If I add a @ before the if, I get an error.

@foreach (var cp in ComponentPresentations) {
    if (cp.Template.Title == "Identification") {                          

            @* THE PROBLEM IS HERE *@
            if (cp.Component.facebook.title != null) {
                <meta property="og:title" content="@cp.Component.facebook.title" >

Someone can help me?

  • And the error is??????
    – Dominic Cronin
    Feb 19 '14 at 12:13
  • Adding a @ in front of the if should work - what error do you get? It may be getting confused by the lack of closing meta tag
    – Will Price
    Feb 19 '14 at 12:13
  • Think that's it Will. <text><meta....></text> should fix it then.
    – Dominic Cronin
    Feb 19 '14 at 12:15

You need to use an @ before the if - Razor treats everything as markup until it encounters an @, then it treats it as code, until it finds something it thinks is markup (like an HTML tag) until it finds something like code again (like a closing HTML tag and then a closing brace }). The error you get is probably as Razor doesn't find a closing </meta> tag, so gets a bit confused as to whether the closing brace is markup or code. You can fix this by closing the meta tag:

<meta property="og:title" content="@cp.Component.facebook.title" />

Or, like Dom suggests using a <text/> element

<text><meta property="og:title" content="@cp.Component.facebook.title"></text>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.