Example of Extension Method, to add "current" or "active" class to Link
Opened this issue · 2 comments
I'm posting this here as it might be useful for someone else.
The extension method checks the page being viewed against the UDI stored on the link.
It can then be used as follows:
<a class="@(link.IsCurrent() ? "current" : null)" href="@link.Url">@link.Name</a>
using Umbraco.Web;
using RJP.MultiUrlPicker.Models;
namespace Your.Project
{
using Umbraco.Core;
public static class MultiUrlPickerLinkExtensions
{
public static bool IsCurrent(this Link value)
{
if (value.Udi != null)
{
var umbracoHelper = new UmbracoHelper(UmbracoContext.Current);
var currentKey = umbracoHelper.AssignedContentItem.GetKey();
var guidUdi = value.Udi as GuidUdi;
return (guidUdi?.Guid == currentKey);
}
return false;
}
}
}
I do wonder if there are performance impacts of GetKey()
, I'm not sure, but the UDI doesn't seem to be in the XML cache.
Keep in mind this only works for LinkType.Content
, so you could check this before (unnecessarily) initializing the UmbracoHelper
.
Even better would be to use the UmbracoHelper
from the UmbracoViewPage
itself, that way you also avoid multiple common pitfalls: https://our.umbraco.org/documentation/reference/Common-Pitfalls/#static-references-to-web-request-instances-such-as-umbracohelper.
Or just pass the IPublishedContent
to the IsCurrent
method, like: @link.IsCurrent(Model)
? So your method would become something like this (not tested):
public static bool IsCurrent(this Link link, IPublishedContent content)
{
if (link == null) throw new ArgumentNullException(nameof(link));
if (content != null && link.Type == LinkType.Content && link.Udi is GuidUdi key)
{
return key.Guid == content.GetKey();
}
return false;
}
I would love to see something like this - maybe even something that allowed using some of the Is-helpers that are available on IPublishedContent
? E.g.:
@foreach (var link in links) {
<li class="@link.IsAncestorOrSelf(Model, "current", null)">
<a href="@link.Url">@link.Name</a>
</li>
}