Create a custom token for a rendering variant
SXA lets you change the way components render by using rendering variants. If you quickly want to extend a rendering variant, you can use the custom resolveVariantTokens
pipeline to extend the set of variant tokens.
A custom token can help you format certain field values and expose more complex data that is not available in normal rendering variant items, for example, because you want to do a transformation on the values of Sitecore items. This can be convenient when, for example, you want to display the parent item field in a rendering variant of the PageList component.
To create a custom token for a rendering variant:
-
Define your own token by adding an additional processor to the
resolveVariantTokens
pipeline. First, create the token processor. For example,$parentName
:RequestResponsepublic class ResolveParentName : ResolveVariantTokensProcessor { public override string Token => "$parentname"; public override void ResolveToken(ResolveVariantTokensArgs args) { // this if statement is quite important in order to support this token in JSON Variants if (args.ResultControl != null) { args.ResultControl.Controls.Add(new LiteralControl { Text = args.ContextItem.Parent.Name }); } else { args.Result = args.ContextItem.Parent.Name; } } }
-
Register the processor in the
resolveVariantTokens
pipeline:RequestResponsepipelines <resolveVariantTokens> <processor type="YOUR_NAMESPACE.ResolveParentName, YOUR_ASSEMBLY" resolve="true" /> </resolveVariantTokens> </pipelines>
-
To apply the token, in the Content Editor, navigate to the rendering variant that you want to add the token to and, in the Token field, enter the custom token using the $ key.