1

In my code, if the Link field target Item matches the context item I want to add CSS class as active and also add the attribute aria-current=page.

Is there a way to add custom attributes to the Glass Mapper Link?

 foreach (var languageResource in languageResourcesList.Children)
      {
        var languageResourceItem = new MvcContext().SitecoreService.GetItem<LanguageResources>(languageResource.Id);
        Glass.Mapper.Sc.Fields.Link linkField = languageResourceItem.LanguagePageLink;
        if (linkField != null)
        {
          var targetItemId = linkField.TargetId;
          if (targetItemId == Sitecore.Context.Item.ID.ToGuid())
          {
            linkField.Class = "active";
           // add attribute aria-current=page to the Link field
          }
        }
        languageResources.Add(languageResourceItem);
      }

Cshtml:

@using (Html.Glass().BeginRenderLink(@languageResource, y => y.LanguagePageLink, isEditable: true))
                {
                    <span class="label">@languageResource.LanguageLabel</span>
                    <span class="lang" lang="@languageResource.LangaugeCode">@languageResource.NativeLanguageLabel</span>
                }

Expected output:

<a href="/xx/xx/xxx" aria-current="page" class="active">
  <span class="label">Chinese</span><span class="lang" lang="ch">中文</span>
</a>

1 Answer 1

1

In your code, you can add Custom Attribute to the Glass Mapper link as below:

new { @class = "active", @aria-current = "page"}

@using (Html.Glass().BeginRenderLink(@languageResource, y => y.LanguagePageLink, new { @class = "active", @aria-current = "page"}, isEditable: true))
            {
                <span class="label">@languageResource.LanguageLabel</span>
                <span class="lang" lang="@languageResource.LangaugeCode">@languageResource.NativeLanguageLabel</span>
            }

You can apply conditions-based classes as well, for active or not.

1
  • 1
    I want to do it in the code (repository) at the field level. I am trying to avoid writing the logic on the cshtml if (targetItemId == Sitecore.Context.Item.ID.ToGuid()) { linkField.Class = "active"; // add attribute aria-current=page to the Link field }
    – Renuka
    Aug 19, 2021 at 17:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.