5

I have a General Link field in Sitecore that I would like to append some HTML to.

I know that I can create a custom extension method and put what I want after the link's text by doing the following:

public static HtmlString CallToActionButton(this SitecoreHelper helper, string fieldName, object parameters)
{
    if (helper == null)
    {
        throw new System.ArgumentNullException("helper");
    }
    return new HtmlString(helper.BeginField(fieldName, null, parameters).ToString() + " <em>text within the link, but after the default text</em>" + helper.EndField().ToString());
}

But what I don't know is how to include the text within the link, but before the default text.

So the above would give me:

<a href="https://example.com/">
  Link text defined in Sitecore
  <em>text within the link, but after the default text</em>
</a>

but I want:

<a href="https://example.com/">
  <em>text within the link, but after the default text</em>
  Link text defined in Sitecore
</a>

What would the extension method be to append HTML before the default link text?

1 Answer 1

5

You'd basically want to override the text element in the field renderer:

Something along these lines:

@{
    var linkField = (LinkField) Model.Item.Fields[fieldname];
}
@Html.Sitecore().Field(fieldname, new {
    text = " <em>Before the text: </em>" + linkField.Text 
})

More examples: https://marcotanainsights.wordpress.com/2017/10/05/tips-on-using-html-sitecore-fields-parameters-object/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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