Thursday, May 24, 2012

Link to top level of a site collection Using SPUrl

Recently I was coding a branding package that deployed several master pages, image files and css files. The package was scoped to the site collection level, of course.

In addition to the top level site collection, there were multiple site collections located in various managed paths. I made sure my package deployed the relevant files to the root of each site collection in the Style Library and master page gallery. The next step was to make sure that the master pages were properly referencing the files in that site collection, and not in the root site collection.

A link such as shown below will not work. It will point to the Style Library at the root site collection, not necessarily to the Style Library where the feature is being installed.

<div class="interiorHeaderLogo"><a href="/"><img src="/Style Library/InteriorPageBrandingPackageAssets/images/interiorTopBar.png" border="0" style="background-position:left top"></a></div>

Many blogs correctly pointed out that I needed to use SPUrl  and reference the site collection. The problem was getting the syntax right. Most examples I found were relatively simple and were focused on simple links. I was dealing with a clickable image, which is a little more involved. Incorrect syntax will throw an error similar to:

Parser Error
Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.


Parser Error Message: Literal expressions like '<% $SPUrl:~SiteCollection/%>' are not allowed. Use  <asp:Literal runat="server"  Text="<%$SPUrl:~SiteCollection/%>" />   instead.


The proper form for the link above is:

<div class="interiorHeaderLogo">
<asp:Literal runat="server" text="<a href=&quot;/&quot;> <img src=&quot;"/>
<asp:Literal runat="server" text="<% $SPUrl:~sitecollection/Style Library/InteriorPageBrandingPackageAssets/images/interiorTopBar.png%>"></asp:Literal>
<asp:Literal runat="server" text="&quot;/&gt;&lt;/a&gt;"/>
</div>