SharePoint Config

Ari Bakker's thoughts on customising and configuring SharePoint 2007 and 2010

Relative URLs in SharePoint

with one comment

If you are referencing resources such as style sheets, images, JavaScript etc in a SharePoint environment you need to be careful to ensure that URLs are relative to the current site (or site collection) so that if sites are moved the references don’t break. For example if you are referencing a style sheet from a master page in a publishing site you will probably want the link to be relative to the site collection so that sites below the root still reference the style sheets at the top level.

In code you can get a reference to the current site or site collection using SPContext.Current.Web.ServerRelativeUrl (site) or SPContext.Current.Site.ServerRelativeUrl (site collection).

You can also do this in your master pages, page layouts or other pages on the site by using the SPUrl expression prefix provided by the Microsoft.SharePoint.Publishing.WebControls.SPUrlExpressionBuilder class. Examples are shown below:

<link rel="stylesheet" type="text/css" href="<% $SPUrl:~SiteCollection/Style Library/Provoke/main.css %>" runat="server">

<link rel="stylesheet" type="text/css" href="<% $SPUrl:~Site/Style Library/Provoke/main.css %>" runat="server">

The first example would always look for the style sheet in the Style Library at the root (top level) site. The second example would look for the style sheet in the current site’s Style Library. This concept can also be applied to other HTML elements such as images and ‘a’ tags as long as they include the runat=”server” attribute.

The other way of doing this is to store your resources in the wpresources folder (or any other folder) in the web application directory (located at C:\Inetpub\wwwroot\wss\VirtualDirectories\80\wpresources by default). You can then access these files from pages or web parts in your sites using

<link rel="stylesheet" type="text/css" href="/wpresources/Provoke/MediaWebPart/main.css">

This is not stored in the SharePoint content databases but can be useful if you are creating custom web parts that are shared across multiple sites or site collections and want a central place for storing resources. It can also aid development as it is easy to create a post build script to copy these files from visual studio into the correct place.

Post to Twitter Post to Delicious Post to Digg Post to Reddit Post to StumbleUpon

Written by Ari Bakker

September 19th, 2007 at 11:37 am

One Response to 'Relative URLs in SharePoint'

Subscribe to comments with RSS or TrackBack to 'Relative URLs in SharePoint'.

  1. An error occurred during the processing of . The expression prefix 'SPUrl' was not recognized. Please correct the prefix or register the prefix in the <expressionBuilders> section of configuration.

    even if i am using runat="server"

    sandeep

    26 Mar 08 at 9:26 pm

Leave a Reply