Relative datasources in Sitecore templates using queries

There are occasions when you setup datasources that you want things to be looked up in a relative manner (rather than binding to specific ID or path). Sitecore has a concept of queries that makes this easy, but sometimes they can be a little confusing. Here I go through an example of why you may want to use a relative query and what it might look like.

Say you have an item that isn’t specific to any site (and therefore may be present in multiple sites), but you’d like to setup the datasource in a way that the context remains specific to the current site. An example might be specifying a datasource for a “Contributor” field on an item and having it reference the local “Team” portion of the site (thank you LaunchSitecore for making this example so easy!). Case in point, you may have something such as the following:

Contributors referencing Team

Currently, the data template is setup to point specifically to /sitecore/content/Home/Team, but if we were to add another site, this would be a problem!

Article data template

However, if we change it to something like the following (the first ID is that of the Home template, and the second ID is that of the Team Member template):

query:./ancestor-or-self::*[@@templateid='{F26BC214-E196-4EAA-82BD-3DF7F45D3699}']//*[@@templateid='{D84642E0-9BA7-4E1B-9E8D-737D5CB420DE}']

The outcome is the exact same, but now it’s referencing content in the current site. If I were to add a Home2 and maybe rename Team to Developers, because it’s still driven by template ID (and we’re not using a relative reference), the Contributors field on the Article will still reflect the appropriate options. See for yourself:

Relative lookup works

As a tiny disclaimer, LaunchSitecore isn’t a huge website (content-wise) so using a query was an easy decision. However, if you’re working on a large website you may need to either be more specific (and target nodes based on an instance-wide convention) or use another method altogether. I’ll leave that up to you, but thought I should mention it.

Flattr this!

Brad Christie

Software programmer from New Hampshire who enjoys the challenge and fulfillment of accomplishing any size task with ingenuity and persistence. I currently work at Sitecore as a Solutions Architect and an MVC evangelist.

  • Nidhi Sinha

    Good Article….So in case of Multisites we need to configure both DataSource field and DataSource Location field in the same way ….Isn’t it ?