Quantcast
Channel: Greg McMullen » code
Viewing all articles
Browse latest Browse all 3

Updated Structured Umbraco Page Titles

$
0
0

Since creating the first rendition of the Structured Page Titles for Umbraco, I decided it would be worthwhile to revisit and clean up the size of the file and make it much more readable.

To use this code you will need to create a shortPageTitle and pageTitle in your document type(s).

First off, we need to declare our global variables. This pulls in the current page’s level as well as setting up the `current` variable for use later on.

var pageLevel = @Model.Level;
var current = "";

Next we break into the loop to filter through all the pages. This is also where we start to breakdown the conditional statements to display what we want, when we want it.

We open the “for loop” using the current pageLevel, decreasing by 1 until we reach 1. We want to include 1 so we grab the Homepage’s title as well.

for (var i = pageLevel; i >= 1; i--){
}

Within the loop, we include `divider`, to select the separator we want between the page names. For mine, I used | and – . Other than that, I put “” at the end to make sure we have nothing after the site title, this was a huge point of frustration and elation once I figured it out.

var divider = (i == 2) ? " | " : 
              (i > 2) ? " - " : "";

After defining divider you can form the title tags. As you can see, this code has a lot going on. For our site, we have a dedicated Homepage title that is longer than we want for child pages. We used shortPageTitle on the homepage node and access it by checking if shortPageTitle exists AND if we are NOT on the homepage. Otherwise, it displays the shortPageTitle & Divider, or the Page title (if it has a value) or the Page Name if everything else is blank.

current += (Model.AncestorOrSelf(i).HasValue("shortPageTitle") && pageLevel != 1) ?  Model.AncestorOrSelf(i).shortPageTitle + divider : 
             (Model.AncestorOrSelf(i).HasValue("pageTitle")) ? Model.AncestorOrSelf(i).pageTitle + divider : 
             Model.AncestorOrSelf(i).Name + divider;

That’s about it, I’m open to feedback and improvements, and you can find the full code available for download and review below!

Full Code

@using umbraco.MacroEngines
@inherits umbraco.MacroEngines.DynamicNodeContext
@{
  var pageLevel = @Model.Level;
  var current = "";
  for (var i = pageLevel; i >= 1; i--){
    var divider = (i == 2) ? " | " : 
                  (i > 2) ? " - " : ""; 
    current += (Model.AncestorOrSelf(i).HasValue("shortPageTitle") && pageLevel != 1) ? Model.AncestorOrSelf(i).shortPageTitle + divider :
               (Model.AncestorOrSelf(i).HasValue("pageTitle")) ? Model.AncestorOrSelf(i).pageTitle + divider :
                Model.AncestorOrSelf(i).Name + divider;
}
  var pageTitle = current;
}
@pageTitle

Viewing all articles
Browse latest Browse all 3

Latest Images

Trending Articles





Latest Images