NotificationSubscribers - Part 2 - Assigning the Title of a News Item to the Page Title
Inspired by a quick "note-to-self" type of post by Nicolai from Dynamicweb in the Dynamicweb forum, I wrote a quick demonstration of assigning the title of a news item to the title of the page.
By default, the title of a page containing the News module takes the title of the page that you assign to it in the Dynamicweb admin interface. However, from a SEO perspective and to make bookmarking a little easier, it's a good idea to assign unique titles to web pages. So, on the details page for a news item, you ideally want to assign the title of the news item to the entire page. With current versions of Dynamicweb (up to 19.1.0.5) this is not the case. However, today a patch was submitted that fixes this behavior automatically. Until the release with the fix comes out, or for cases where you're stuck on an older version of Dynamicweb, you can implement this behavior yourself using the following code:
using System; using Dynamicweb.Extensibility; using Dynamicweb.NewsV2; using Dynamicweb.NewsV2.Extensibility; namespace Dynamicweb.Samples.Lib { [Subscribe(Dynamicweb.Notifications.NewsV2.Frontend.AfterSelectData)] public class AssignNewsTitleToPage : NotificationSubscriber { public override void OnNotify(string notification, NotificationArgs args) { if (args == null || !(args is FrontendDataNotificationArgs)) { return; } FrontendDataNotificationArgs item = (FrontendDataNotificationArgs)args; NewsItem newsItem = item.Data as NewsItem; if (newsItem == null || !(newsItem is NewsItem)) { return; } Dynamicweb.Frontend.PageView.Current().Meta.Title = newsItem.NewsHeading; } } }
This code fires right after Dynamicweb is done selecting the news item. It's an ideal location to be notified, as you can grab an instance of the NewsItem that is about to be displayed. Since the same NotificationSubscriber also fires for a list of news items, you need to check the Data property of the FrontendDataNotificationArgs class that is passed to the OnNotify method. If it's a NewsItem, you can grab its NewsHeading property and assign it to the title of the current Pageview instance (which you can retrieve using Pageview.Current()).