Skip to content

Instantly share code, notes, and snippets.

@jamiepollock
Last active October 8, 2019 15:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamiepollock/d51c744ed3df44f8e5430ba405602800 to your computer and use it in GitHub Desktop.
Save jamiepollock/d51c744ed3df44f8e5430ba405602800 to your computer and use it in GitHub Desktop.
Umbraco XPath query with tokens
using System.Web.Mvc;
using Umbraco.Web.Models;
using Umbraco.Web;
using Umbraco.Core.Xml;
using Umbraco.Web.Mvc;
namespace MyWebsite.Controllers
{
public class MyController : RenderMvcController
{
public override ActionResult Index(RenderModel model)
{
var siteRoot = model.Content.Site();
var tokens = new[] { new XPathVariable("rootId", siteRoot.Id.ToString()) };
var blogPosts = Umbraco.TypedContentAtXPath("id($rootId)[@isDoc]//blogPost", tokens);
//Do something with blog posts before passing a model to the view.
var viewModel = new MyViewModel {
posts = blogPosts
};
return View(viewModel);
}
}
}
@naepalm
Copy link

naepalm commented Mar 24, 2017

So useful, thank you! The only thing I changed was to use Chriztian's suggestion of id($rootId) instead of //*[@id = $rootId] :)

@jamiepollock
Copy link
Author

jamiepollock commented Mar 24, 2017

@naepalm no worries :) I've updated my gist to include Chriztian's suggestion. That looks a lot cleaner now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment