Access document type value within master template
# help-with-umbraco
m
I have a page document type used as the "template" for render of sub pages. In this document type, I have a property called "title" which obviously is the located in the master.cshtml - I have tried to insert this value using the "Insert" value in settings, it picks up the value, however, the remains blank although the document type value for the selected page is set. I assume then that because this property is set on the actual template, it's not available in the master template. How do I get access to this property within the master template?
k
Not sure what "template" means here. But in the master razor, could you do something like
UmbracoContext.PublishedRequest.PublishedContent.GetProperty("title")
etc? This would get a property from the "current page" regardless of its document type. We sometimes do this in our layout razors since they're just
UmbracoViewPage
, not
UmbracoViewPage<Something>
.
If you use actual document type and template inheritance instead of compositing, you could have the
title
property on the top-level document type and it would be inherited down. But I wholeheartedly recommend against using doctype and template inheritance, in favor of compositing.
s
If you really want to have strongly typed models, you could do this as follows: In your
master.cshtml
at the point where you want your
<title />
to be rendered, add:
@await RenderSectionAsync("title")
. This will force any template inheriting from the master to insert a title section which would look something like:
Copy code
html
@section title {
    <title>@Model.Title</title>
}
However, I think you just want to try this in your master template:
<title>@Model.Value("title")</title>
The
"title"
here is the alias of your Title property. Do note, however that the Title property needs to be available on the document type for this template, so you might need to do a recursive scan and fall back to the parent title or a title even higher up. Depends a bit on your scenario.
s
Or you could put the title property in a composition and cast the umbraco.assignedcontent to ITitle
k
This is what we do. In reality, we don't know in runtime that the "current page" actually composes in
ITitle
, so it feels like a bit of a hack. But still preferable to actual document type inheritance.
s
Compositions for the win!
2 Views