How To Get The Home Page In Umbraco?

One common requirement on every Umbraco build is getting a reference to the homepage from your code.  On most website builds, you may only have one node as the

Content
-- Homepage
-- Page One
-- Page Two

In these scenarios you can use this snippet to get the homepage:

Umbraco.TypedContentAtRoot().First();

If you have a slightly more complex website where you may have multiple websites in a single Umbraco instance, you have a complex mega-menu that needs to be defined in its own section or even a setting page to store global data.

Content
-- Homepage
-- Page One
-- Page Two
-- Mega Menu
-- Settings Page

The above code might not necessarily return the homepage as you have multiple pages at the content level.  Instead, we would have to filter out the results.  One way to do this is via the document type alias, using a hardcoded string is a bit risky in-case a content editor ever updated the name.  A safer approach is to use the homepages content id.  In Umbraco you go to the ‘Properties’ tab for the homepage in the content section,

Umbraco_document_type_id

@{
var rootNodes = Umbraco.TypedContentAtRoot();
var homeNodeByAlias = rootNodes.First(x => x.DocumentTypeAlias == "umbHomePage");
var homeNodeById = rootNodes.First(x => x.Id == 1077);    
}

Conclusion

In today’s guide, we’ve covered how to get a reference to the homepage from the Umbraco 7 API.  If you only have a single item at the top of your content tree, then you can simply use Umbraco.TypedContentAtRoot().First().  If you have more than one page located at that level, then you will need to filter the results to get the page you want.  I would recommend using the Id property, but you could also use the document type alias or even the document type id.

Jon D Jones

Software Architect, Programmer and Technologist Jon Jones is founder and CEO of London-based tech firm Digital Prompt. He has been working in the field for nearly a decade, specializing in new technologies and technical solution research in the web business. A passionate blogger by heart , speaker & consultant from England.. always on the hunt for the next challenge

More Posts

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *