Tuesday, November 6, 2012

Relative Paths in SharePoint 2010 using $SPUrl


Relative Paths in SharePoint using SPUrlExpressionBuilder ($SPUrl)

When you edit pages and/or master pages in SharePoint either for branding or some other project you will eventually come across the need to link to some resource file whether it’s an image, icon, CSS, etc. When this came up for me, I realized I had no idea how to do this properly.
Fortunately, some quick searching found the solution I needed. I came across Bugra Postaci’s blog post on the subject and that got me going. Be sure to check it out for some background, but the basic idea is to use theSPUrlExpressionBuilder class to generate relative links. Unfortunately, this class is part of the publishing namespace and so is only available in SharePoint Server (2010) and MOSS (2007).
He gives an example of linking to an image within the Style Library of the site collection using the following code directly within the master page:
<asp:Image ImageUrl="<% $SPUrl:~sitecollection/Style Library/CustomImages/BlogofBugra.jpg %>" runat="server" />
The key thing to note is the inline use of the $SPUrl command. The example shows this within an asp:Image control but this can be done in a standard tag as well (img, link, etc.).
After seeing that, I really wanted to know what other magic tokens you can use, but the Microsoft Documentaiton on the class doesn’t even show the inline $SPUrl syntax, let alone list any of the usable tokens! Doing a quick search will find you an assortment of undocumented tokens. However this can be misleading as the tokens listed in {} braces are generally only for custom actions and not for inline links (you can find examples of those lists here and here).
Token
Replaced By
Version
~site/
2007, 2010
~sitecollection/
2007, 2010
~language
2007, 2010
With the exception of the ~language token, the others are replaced using a call to Microsoft.SharePoint.Utilities.SPUtility.UrlFromPrefixedUrlCore.

No comments:

Post a Comment