Skip to content

Instantly share code, notes, and snippets.

@jonathanread
Created August 24, 2018 21:04
Show Gist options
  • Save jonathanread/d1ba7b0d936a95834f6daea08fbf8d5b to your computer and use it in GitHub Desktop.
Save jonathanread/d1ba7b0d936a95834f6daea08fbf8d5b to your computer and use it in GitHub Desktop.
Render OG Fields to Page Head
using SitefinityWebApp.Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Routing;
using Telerik.Sitefinity.Abstractions;
using Telerik.Sitefinity.Data;
using Telerik.Sitefinity.Frontend;
using Telerik.Sitefinity.Frontend.Navigation.Mvc.Models;
using Telerik.Sitefinity.Services;
using Telerik.Sitefinity.Web.Events;
using Telerik.Sitefinity.Model;
using Telerik.Sitefinity;
using Telerik.Sitefinity.Libraries.Model;
using System.Web.UI.HtmlControls;
using System.Web.UI;
namespace SitefinityWebApp
{
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
SystemManager.ApplicationStart += SystemManager_ApplicationStart;
}
private void SystemManager_ApplicationStart(object sender, EventArgs e)
{
EventHub.Subscribe<IPagePreRenderCompleteEvent>(this.OnPagePreRenderCompleteEventHandler);
}
private void OnPagePreRenderCompleteEventHandler(IPagePreRenderCompleteEvent evt)
{
TryAddMetaField(evt, "og:title", "OGTitle");
TryAddMetaField(evt, "og:description", "OGDescription");
TryAddMetaField(evt, "og:image", "OGImage");
string ogSiteName = "og:site_name";
if (!DoesTagExist(evt.Page, ogSiteName))
{
evt.Page.Header.Controls.Add(BuildOGMetaTag(ogSiteName, SystemManager.CurrentContext.CurrentSite.Name));
}
string ogUrl = "og:url";
if (!DoesTagExist(evt.Page, ogUrl))
{
evt.Page.Header.Controls.Add(BuildOGMetaTag(ogUrl, SystemManager.CurrentHttpContext.Request.Url.ToString()));
}
}
private void TryAddMetaField(IPagePreRenderCompleteEvent evt, string metaFieldIdentifier, string pageFieldIdentifier)
{
var page = evt.Page;
var pageNode = evt.PageSiteNode;
var field = pageNode.GetCustomFieldValue(pageFieldIdentifier);
string fieldValue = string.Empty;
if (field is string)
{
fieldValue = field as string;
}
else if (field is Image img)
{
if (img != null)
{
fieldValue = img.Url;
}
}
if (!fieldValue.IsNullOrWhitespace() && !DoesTagExist(page, metaFieldIdentifier))
page.Header.Controls.Add(BuildOGMetaTag(metaFieldIdentifier, fieldValue));
}
private static bool DoesTagExist(Page page, string tagPropertyTitle)
{
//Sitefinity adds it's OG tags via literals, so we check them here
return page.Header.Controls.OfType<LiteralControl>().Any(control => control.Text.Contains(tagPropertyTitle));
}
private HtmlMeta BuildOGMetaTag(string property, string content)
{
var meta = new HtmlMeta() { Content = content };
meta.Attributes.Add("property", property);
return meta;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment