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.