5

This is in relation to Add custom attributes to the General Link field and have it work in Experience Editor and Content Editor

I would like to get Glass Mapper to automatically render the custom attributes the content editor sets on a General Link field.

This should handle internal ,external and anchor links and be able to render a checkbox field NoFollow and a Dataattributes field which is a single link.

href="/test" data-toggle="modal" data-target="#orderModal" data-backdrop="static" data-keyboard="false" rel="nofollow"

Is there a way I could customize Glass and the developers do not have to add code on each rendering?

5

Before implementing this solution you will need to download the latest nightly. I made a couple of changes to make it easier to solve this problem.

Ok, firstly create a sub-type to map the additional link attributes onto, e.g.:

public class MyLink:Glass.Mapper.Sc.Fields.Link{
   public string MyAttribute{get;set;}
}

Then create a new DataMapper:

public class SitecoreFieldMyLinkMapper : SitecoreFieldLinkMapper
{
    public SitecoreFieldMyLinkMapper()
        : base(new UrlOptionsResolver(), typeof(MyLink))
    {

    }

    public override object GetField(Sitecore.Data.Fields.Field field, SitecoreFieldConfiguration config,
        SitecoreDataMappingContext context)
    {
        if (field == null || field.Value.Trim().IsNullOrEmpty()) return null;

        MyLink link = new MyLink();
        LinkField linkField = new LinkField(field);

        MapToLinkModel(link, linkField, config);

        link.MyAttribute = linkField.GetAttribute("something");

        return link;

    }
}

Then create a HTML extension:

public static class HtmlExtensions
{
    public static string RenderMyLink<T>(this IGlassHtml html, T model, Expression<Func<T, object>> field,
        bool isEditable = false, string contents = null)
    {
        var myLink = html.GetCompiled(field).Invoke(model) as MyLink;

        return html.RenderLink(model, field, new {data_type = myLink.MyAttribute}, isEditable, contents);
    }
}

Again this only works with the latest nightly because I made some changes to support this. If you don't want to use the nightly you will need to copy and paste some code from the SitecoreFieldLinkMapper and the GlassHtml classes.

  • Mike thank you for the comment but the data attributes can be different per link and I really do not want the devs hardcoding it in the view. – ASura Sep 20 '17 at 16:13
  • Mike thank you for the updated answer. I was hoping not to do it via HTMLExtension but create a custom glass view which will handle it. In that case the developer just has to inherit it in the view. I might also want to do begin render link as well. – ASura Sep 22 '17 at 15:01

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.