In today’s content-driven web landscape, personalization and dynamic content are more important than ever. Sitecore enables content editors and developers to seamlessly inject dynamic values into rich text or multi-line text fields using custom tokens. In this blog, we explore how you can leverage $ProductName, $ProductPrice, and $ProductType tokens on a Product Details Page. These tokens pull data directly from a Product Template that contains corresponding fields, ensuring the rendered page always reflects the current product information.

Understanding the Product Template

In Sitecore, a Product Template acts as a blueprint for individual product items. Typically, this template includes fields such as:

  • ProductName
  • ProductPrice
  • ProductType

These values are maintained on each product item in the content tree. Instead of hardcoding these values inside rich text editors or multi-line text fields on the Product Details Page, you can insert custom tokens that serve as placeholders. When the page renders, these tokens dynamically substitute the actual product values.

Token-Enabled Fields: Rich Text and Multi-Line Text

The token substitution mechanism in our scenario is intentionally limited to fields that allow for extended text formatting—namely, rich text and multi-line text fields. This design choice ensures that:

  • Content editors have the flexibility to embed dynamic product data within longer narratives or descriptions.
  • Sitecore pipelines can efficiently scan and process the token placeholders without interfering with shorter, more static text fields.

By constraining the token replacement feature to rich text and multi-line fields, you maintain control over where and how dynamic content is injected, thus reducing the risk of unintended substitutions in single-line or other specialized fields.

How Custom Token Replacement Works

The core idea is to implement a custom token processor—either as a Sitecore pipeline processor or within your rendering logic—that scanning the field content for token identifiers ($ProductName, $ProductPrice, $ProductType) and replacing them with the corresponding field values from the product item.

When a content editor inputs text like:

Introducing our latest gadget: $ProductName. Priced at only $ProductPrice, this $ProductType is designed to revolutionize your experience!

Then the custom token processor will:

  1. Identify: Parse the rich text content looking for any supported tokens.
  2. Fetch Values: Retrieve ProductName, ProductPrice, and ProductType values from the current product item.
  3. Replace Content: Inject the actual product data in place of their respective tokens.
  4. Render: The final output rendered to the end user has no tokens but fully substituted, dynamic content.

This mechanism ensures that your product pages are always in sync with the data stored in Sitecore.

The C# Code Implementation

Below is a simplified C# example demonstrating how you might implement a custom token replacement function. This function assumes that you have access to a Sitecore Item representing the product.

using Sitecore.Data.Items;
using System.Collections.Generic;

public static class CustomTokenReplacer
{
    /// <summary>
    /// Replaces custom product tokens in a given input string with values from the product item.
    /// </summary>
    /// <param name="input">Content containing tokens (e.g., rich text fields).</param>
    /// <param name="productItem">Sitecore item representing the product.</param>
    /// <returns>Content with tokens replaced by actual product information.</returns>
    public static string ReplaceProductTokens(string input, Item productItem)
    {
        if (string.IsNullOrEmpty(input) || productItem == null)
        {
            return input;
        }
        
        // Mapping tokens to their corresponding field values
        var tokens = new Dictionary<string, string>
        {
            { "$ProductName", productItem["ProductName"] },
            { "$ProductPrice", productItem["ProductPrice"] },
            { "$ProductType", productItem["ProductType"] }
        };
        
        // Replace each token with its corresponding value
        foreach (var token in tokens)
        {
            input = input.Replace(token.Key, token.Value);
        }
        
        return input;
    }
}

Explanation:

  • The function checks if the content string and product item are valid.
  • It builds a dictionary mapping each token to its corresponding value from the product item.
  • It iterates over the dictionary and replaces the tokens found in the input text.
  • Finally, it returns the updated string, ready for rendering on your Product Details Page.

Patch Configuration Example for Custom Token Processor

In Sitecore it’s common to utilize patch configuration files to register custom pipeline processors. Below is an example patch config file, which you might place in your App_Config/Include folder. This file registers a custom processor to intercept rich text field rendering and perform token replacement:

xml
<?xml version="1.0"?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <pipelines>
      <renderField>
        <!-- Register the custom token processor BEFORE the default rendering processor -->
        <processor type="EZ4Youtech.Sitecore.Pipelines.CustomTokenProcessor, CustomSitecoreTokens"
                   patch:before="*[@type='Sitecore.Pipelines.RenderField.RenderField']">
          <!-- Optional: any configuration parameters for your processor can be included here -->
        </processor>
      </renderField>
    </pipelines>
  </sitecore>
</configuration>

How it works:

  • Processor Registration: The custom processor (e.g., CustomTokenProcessor) is inserted into the renderField pipeline.
  • Ordering: The patch:before attribute ensures that your processor runs at the appropriate point—before the default Sitecore rendering logic kicks in.
  • Customization: You can extend the configuration to pass additional parameters if your token processor requires them.

This patch config seamlessly integrates your custom token processing logic so that every time a rich text or multi-line field is rendered, your tokens are identified and replaced with live product data.

A sequence Diagram of how it works

PlantUML diagram

Best Practices

To ensure a robust implementation and a seamless experience for both developers and content editors, consider the following best practices:

  • Clear Token Conventions: Use a consistent token format (e.g., all tokens start with a $) to avoid conflicts and ease future enhancements.
  • Field Validation: Always check that product items have non-null and valid field values before performing substitutions. This can prevent rendering issues if a product’s data is incomplete.
  • Performance Optimization: Instead of processing tokens on every page load, consider caching the substituted output if the product data does not change frequently. This can be integrated via Sitecore caching strategies.
  • Error Handling: Implement robust error handling and logging within your token processing function. This will help diagnose issues if tokens are missing or field values are misconfigured.
  • Editor Training: Provide clear documentation for content editors on which fields support tokens and how to correctly format the content. This reduces errors and ensures proper usage.

Common Pitfalls and How to Avoid Them

While custom tokens provide powerful dynamic content capabilities, there are a few common pitfalls to be aware of:

  • Over-Replacement: Ensure that tokens are only processed in designated rich text or multi-line fields. Accidentally processing tokens in fields not meant for token replacement could lead to unintended data exposure.
  • Caching Issues: If you employ caching for performance, remember to clear or update caches when product data changes. Otherwise, the rendered content might show outdated information.
  • Field Absence: If a product item is missing one of the key fields (e.g., ProductPrice), the rendered page may display an empty token. To avoid this, incorporate default values or graceful degradation behavior in your processing logic.
  • Security Concerns (XSS): Be cautious when injecting values directly into rich text fields. Always ensure that the dynamic content is properly encoded to safeguard against cross-site scripting (XSS) vulnerabilities.
  • Improper Token Nesting: In cases where tokens may appear nested or adjacent to similar strings, determine a clear precedence or processing order to avoid misinterpretation.