How to Use Enclosingtag With Css Class on Sitecore Field Renderer

How to set css class on enclosing tag for Sitecores field renderer

Posted by Michael Sundstrøm on 2020-03-05

I ran into a bit of a pickle the other day. I was asked to hide the outer tag when a field is empty. That’s easy!!

    @Html.Sitecore().Field(“FieldName”, Model, new { @EnclosingTag=“h2” } )

That works fine when you don’t have a class attribute on the enclosing tag. The code below doesn’t work :(

    @Html.Sitecore().Field(“FieldName”, Model, new { @EnclosingTag=“h2”, @class=“alert-notification__topic” } )

The reason it quite simple. Sitecore does not know which tag the class applies to, therefore it won’t render anything.

A solution that works is this

    @Html.Sitecore().Field(“FieldName”, Model, new { Before=”<h2 class=\“alert-notification__topic\“>”, After=”</h2>” } )

I have some very simple markup here. In more complex scenarios you might consider using a variable to hold the markup string and append it for better readability of the code.