Rob Allen
Rob Allen

Reputation: 2921

sitecore query items by client url

I am looking for a quick and dirty way to query the layouts files of a particular page by its friendly url. This is probably easy, but I can't find the solution.

Basically I want to say something like the following. Pseudo-code:

var mainpage = Sitecore.EasyQueryUtility.GetItemByFriendlyUrl(requestedUrl);

or

var mainpage = Sitecore.EasyQueryUtility.GetOppositeOfFriendlyUrl(friendlyurl);

Upvotes: 2

Views: 2324

Answers (3)

Mark Ursino
Mark Ursino

Reputation: 31435

It sounds like you want to do two things here:

  1. Determine an item based on its rendered URL in the address bar (i.e. friendly URL)
  2. Determine the layout being used by the item once you determine the item.

If those are correct, hopefully this can help you out:

Note: untested code I did on-the-fly

// if you have the full URL with protocol and host
public static Item GetItemFromUrl(string url)
{
    string path = new Uri(url).PathAndQuery;    
    return GetItemFromPath(path);
}

// if you have just the path after the hostname
public static Item GetItemFromPath(string path)
{
    // remove query string
    if(path.Contains("?"))
        path = path.split('?')[0];

    path = path.Replace(".aspx", "");

    return Sitecore.Context.Database.GetItem(path);
}

Once you have the item you can get the layout's name like so:

item.Visualization.GetLayout(Sitecore.Context.Device).Name;

Or the layout's physical file path to the ASPX:

item.Visualization.GetLayout(Sitecore.Context.Device).FilePath;

Upvotes: 1

Marek Musielak
Marek Musielak

Reputation: 27132

If you want to get the path of the aspx file which is used for the layout of your page, you can use:

Sitecore.Context.Item.Visualization.Layout.FilePath

Upvotes: 1

chrislewisdev
chrislewisdev

Reputation: 556

I may have misunderstood you but if you want to control the format of friendly URLs you can set several attributes via the Sitecore.Links.UrlOptions class and pass an instance of this in to the link manager. See here for more details. (Note - the LinkManager class is only available from SiteCore 6 I beleive).

The code you would end up with looks like this:

Sitecore.Links.UrlOptions urlOptions = (Sitecore.Links.UrlOptions)Sitecore.Links.UrlOptions.DefaultOptions.Clone(); 
urlOptions.SiteResolving = Sitecore.Configuration.Settings.Rendering.SiteResolving; 
string url = Sitecore.Links.LinkManager.GetItemUrl(item, urlOptions);

You can then set fields like AddAspxExtension on the urlOptions you pass in.

As you can see, the process is reliant on you passing in an item - whether it be obtained via the current context or retrieved from the URL you start off with.

If you were asking about obtaining the layout definition item, take a look at this which shows you how.

Upvotes: 0

Related Questions