In this tutorial, we will explore how to process fields in a Sitecore context using a custom pipeline processor. Specifically, we will handle LinkField types to ensure that external links include the rel="noopener noreferrer" attribute for enhanced security.
We’ll start by examining the C# code for the ExternalLinks class, which processes the LinkField and adds the necessary attributes. Following that, we’ll look at the corresponding pipeline configuration in the .config file, which integrates our custom processor into the Sitecore renderField pipeline.
By the end of this tutorial, you’ll understand how to create and configure a custom pipeline processor in Sitecore to manage external links effectively. Let’s dive in!
Pipeline C# Code
In this code we process a field in a Sitecore context, specifically handling LinkField types. It ensures that external links have the rel="noopener noreferrer" attribute added for security purposes.
public class ExternalLinks
{
public void Process(RenderFieldArgs args)
{
Assert.ArgumentNotNull(args, "args");
if (Sitecore.Context.Site.DisplayMode == Sitecore.Sites.DisplayMode.Edit) //return;
var field = FieldTypeManager.GetField(args.GetField());
if (field is LinkField linkField)
{
if (linkField.IsInternal || string.IsNullOrEmpty(linkField.Url)) return;
args.Parameters.Add("rel", "noopener noreferrer");
}
}
}
Pipeline .config
And now we have here the configuration of the pipeline. This configuration sets up the ExternalLinks class to be executed as part of the renderField pipeline in Sitecore. It ensures that the ExternalLinks processor runs after the GetLinkFieldValue processor. Additionally, it includes a setting to control the protection of external links with a target="_blank" attribute.
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<settings>
<setting name="ProtectExternalLinksWithBlankTarget" value="false" />
</settings>
<pipelines>
<renderField>
<processor type="Foundation.Infrastructure.Pipelines.ExternalLinks, Foundation.Infrastructure" patch:after="processor[@type='Sitecore.Pipelines.RenderField.GetLinkFieldValue, Sitecore.Kernel']"/>
</renderField>
</pipelines>
</sitecore>
</configuration>
Thanks for reading!
And that's it! We created a custom pipeline processor in Sitecore to handle LinkField types. The ExternalLinks class ensures external links include the rel="noopener noreferrer" attribute for security. We integrated this processor into the renderField pipeline, ensuring it runs after the GetLinkFieldValue processor. This setup helps maintain the security and integrity of external links in your Sitecore application.
If you have any questions or ideas in mind, it'll be a pleasure to be able to be in communication with you, and together exchange knowledge with each other.
Top comments (0)