07 August 2011

SharePoint: Conditionally display content for authors and readers

For a current project, I needed to display an Article Date content field in a page layout. The author could pick a date when in Edit View; the reader would only see the value the author had selected, or nothing if no value had been picked.

To do server-side code blocks in a page layout, we'll first need to enable it from our app's web.config file; otherwise it'll throw an error saying "Code blocks are not allowed in this file," as described here. To enable code blocks, open your app's web.config and locate the PageParserPaths tag, which is empty, and modify it to look like this:


Note the VirtualPath; this needs to point to the location of your page layout (or ASPX) file.

Next, we'll use Bart McDonough's blog post to add the EditModePanel and AuthoringContainer; the nesting of these controls is well explained by Bart:











http://www.blogger.com/img/blank.gif
Note the DateTimeField element; that allows authors to edit the "Article Date" field.

Now we need to add some server-side code to determine if we can display the "Article Date," and to format it properly (this code is based on Johan Leino's blog post):
<%= (Microsoft.SharePoint.SPContext.Current.Item["Article Date"] == null) ? "" : 
"Last update on " + DateTime.Parse(Microsoft.SharePoint.SPContext.Current.Item["Article Date"].ToString()).ToString("d MMMM yyyy") +
"." %>
This code displays the text "Last update on 9 August 2011." if there's a value in the "Article Date" content field; otherwise, it displays nothing.

No comments: