Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sitecore MVC and FieldRenderer.Render for Links

I'm trying to render a general link field like this - FieldRenderer.Render(item, "link").

This works as expected but how do I set custom text within the a tag that gets rendered. I want my output to look something like this

<a href="[link from sitecore]">[custom text from another field]</a>

Basically, the text for the link should come from another field on the item.

Thanks

like image 803
Gabbar Avatar asked Jul 25 '14 14:07

Gabbar


3 Answers

Jason has a great idea, but this functionality is out of the box.

@Html.Sitecore().BeginField("Link Field", new { haschildren= true })
@Html.Sitecore().Field("Text Field")
@Html.Sitecore().EndField()

No need to modify anything at all.

like image 126
Keith Murphy Avatar answered Nov 17 '22 23:11

Keith Murphy


You probably want to try the following:

@Html.Sitecore().BeginField("Link Field")
//custom code
@Html.Sitecore().EndField()
like image 42
Varun Nehra Avatar answered Nov 17 '22 23:11

Varun Nehra


Varun's answer is definitely correct, however you will encounter an issue when the content editor has put a value into the Description field of a General Link. The link renderer will output both the description and whatever is between the BeginField and EndField methods.

A solution would be to allow for an extra parameter (HideDescription) which can hide the description. Two possible solutions for this would be;

  1. Override the standard Sitecore.Xml.Xsl.LinkRenderer class with your own that would stop the description from being put in.
  2. Add a custom pipeline step after the Sitecore.Pipelines.RenderField.GetLinkFieldValue which will do some post rendered processing to remove the description.

Option 2 is less invasive but is a little more difficult to make sure the results are 100%. Once you have this you can then render fields like the following;

@Html.Sitecore().BeginField("Link Field", new { HideDescription = true })
@Html.Sitecore().Field("Text Field")
@Html.Sitecore().EndField()
like image 2
Jason Bert Avatar answered Nov 17 '22 21:11

Jason Bert