December 16, 2014

Anchor in Tridion Component links

In Tridion Link Anchor (jump to specific section of the page) is very tricky. there is an out of the box anchor option. let discuss that first.

Anchor OOTB : In component link there is an attribute "Add Anchor"

<tridion:ComponentLink runat="server" PageURI="tcm:85-159563-64" ComponentURI="tcm:85-159309" TemplateURI="tcm:0-0-0" AddAnchor="true" LinkText="internal link test" LinkAttributes=" title= &#34;alt text for link &#34;" TextOnFail="true"/>

when this AddAnchor = true is set. Tridion CD will create anchor for particular components as per their position of the page.

e.g following is a Tridion page sompage.aspx having three components Comp 1 and Comp 2 and Comp 3

------------
Comp 1
---------
Comp 2
---------
Comp 3
---------------

e.g you use comp2 as component link on another page. it will be resolved as somepage.aspx#1
so this is as per the position of the component on page.

another catch is you have to create <a id="1"> on somePage explicitly using your templates. this is not automated.

Custom solution:
As OOTB solution is base on numbers only. if you want to based it on some text e.g #Intro. you need some customization for it.

I have develop & tested this small solution for it.
------------------------------------------------------------------------------------------------------------
namespace  CD.Web.ComponentLink.Extensions
{
    public class ComponentLink : Tridion.ContentDelivery.Web.UI.ComponentLink
    {
        [DefaultValue("None")]
        [Bindable(true)]
        [Category("Appearance")]
        public string AnchorName { get; set; }


        protected override void Render(HtmlTextWriter writer)
        {
            if (HttpContext.Current == null || HttpContext.Current.Application == null)
                return;
            using (var compLink = new Tridion.ContentDelivery.Web.Linking.ComponentLink(new TcmUri(ComponentUri).PublicationId))
            {
             
                var link = compLink.GetLink(PageUri, ComponentUri, TemplateUri, LinkAttributes, LinkText, TextOnFail, AddAnchor);
                link.Anchor = AnchorName;
             
                string linkAsString = link.ToString();
                writer.Write(linkAsString);
                this.RenderChildren(writer);
            }
        }

    }

}
------------------------------------------------------------------------------------------------------


  • Register above custom control in your website's web.config 
  • Update schema to accept the Anchor from Editor
  • Update template code to pass this anchor name as mention below

<Rk:ComponentLink runat="server" PageURI="tcm:85-159563-64" ComponentURI="tcm:85-159309" TemplateURI="tcm:0-0-0" AnchorName="true" AddAnchor="false" LinkText="internal link test" LinkAttributes=" title= &#34;alt text for link &#34;" TextOnFail="true"/>

do post comments if you have any questions.

No comments: