@Html.Sitecore().Field(TPage.Headline) when @Html.Sitecore().Field(TPage.Headline) contains a value but" /> @Html.Sitecore().Field(TPage.Headline) when @Html.Sitecore().Field(TPage.Headline) contains a value but" /> @Html.Sitecore().Field(TPage.Headline) when @Html.Sitecore().Field(TPage.Headline) contains a value but"/>

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

671 Views Asked by At

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?

2

There are 2 best solutions below

3
Jay S On BEST ANSWER

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.

1
Mattias Lindblom On

Thanks @Jay S, so far I've ended up with:

@if( Sitecore.Context.PageMode.IsExperienceEditor)
   || Model.Item.FieldHasValue(TPage.Headline)
{
    <h1 class="page-heading">@Html.Sitecore().Field(TPage.Headline)</h1>
}
@if ( Sitecore.Context.PageMode.IsExperienceEditor
      || Model.Item.FieldHasValue(TPage.Ingress))
{
    <p class="ingress">@Html.Sitecore().Field(TPage.Ingress)</p>
}

It works but I don't like the clutter, would've preferred two one liners instead of 8-10 rows.