So I was working on a sublayout earlier today and I ran across a piece of HTML that made me say, “Hmmm…, what is the best way to tackle this situation”? I had the HTML below to work with for the “Page Title” and “Sub Title” fields that were to be simply rendered in a FieldRenderer control.
<h1>My Account <small>Manage your account online</small></h1>
The title “My Account” would always exist but the “Manage your account online” in the <small> element would be optional for the Content Editor to use to display sub-titles. Well, I am a programmer who likes to leave no markup behind so I quickly remembered the EnclosingTag property of the FieldRenderer that made perfect sense in this situation. Below is the markup I used to pull in the fields:
<h1> <sc:FieldRenderer runat="server" FieldName="Page Title" ID="frPageTitle"></sc:FieldRenderer> <sc:FieldRenderer runat="server" FieldName="Sub Title" ID="frSubtitle" EnclosingTag="small"></sc:FieldRenderer> </h1>
Instead of leaving the <small> HTML element in the markup on the page if the “Sub Title” field is blank, I used the EnclosingTag property to ensure that if there is a value to render it inside the <small> HTML element. However, if the field is blank then don’t display the <small> HTML element either. Pretty slick when you need it sometimes! Happy coding!