htmlsitecorefrontendsitecore-mvcsitecore8.2

How do I add a css class to enclosing tag in sitecores MVC HtmlHelper for fields?


I want to render <h1 class="page-heading">@Html.Sitecore().Field(TPage.Headline)</h1> when @Html.Sitecore().Field(TPage.Headline) contains a value but also I doesn't want to render the enclosing tag <h1 class="page-heading"> when the field are empty.

Using @Html.Sitecore().Field(TPage.Headline, new { @class="page-heading", EnclosingTag="h1"}) almost does what I want but it doesn't include the css class.

How do I specify a class name for the enclosing tag using the Sitecore HTML helper? Or are there another way to avoid rendering empty tags?


Solution

  • I'm not sure how to do it with the Field helper method, but the old-school way of doing things could be done like this:

    @if(!String.IsNullOrEmpty(TPage.Headline)){
       <h1 class="page-heading">@Html.Sitecore().Field(TPage.Headline)</h1>
    }
    

    In your case, you don't have anything to output when the field is empty, so a simple IF check should work.