Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Example of Extension Method, to add "current" or "active" class to Link #68

Open
uniquelau opened this issue Dec 6, 2017 · 2 comments

Comments

@uniquelau
Copy link
Contributor

uniquelau commented Dec 6, 2017

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.

@ronaldbarendse
Copy link
Contributor

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;
}

@greystate
Copy link

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>
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants