Is there any way to render Name value list field using rendering variant fields?
1 Answer
Depending on what you want to achieve. If you will use standard Variant Field you will see something like this:
for such field:
If you want to have a more fancy look & feel I would suggest writing your own Variant Token. A sample implementation can look like this:
public class ResolveNameValueList : ResolveVariantTokensProcessor
{
public override string Token => "$nameValueList";
public override void ResolveToken(ResolveVariantTokensArgs args)
{
string content = GetContent(args);
if (args.ResultControl != null)
{
args.ResultControl.Controls.Add(new LiteralControl
{
Text = content
});
}
else
{
args.Result = content;
}
}
protected virtual string GetContent(ResolveVariantTokensArgs args)
{
string content = string.Empty;
var field = args.ContextItem.Fields["List"];
if (!string.IsNullOrEmpty(field?.Value))
{
CustomField customField = FieldTypeManager.GetField(field);
if (customField is NameValueListField)
{
NameValueListField nameValueList = customField as NameValueListField;
foreach (string key in nameValueList.NameValues.Keys)
{
content += $"<div>{key}: {nameValueList.NameValues[key]}</div>";
}
}
}
return content;
}
}
And registration:
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<pipelines>
<resolveVariantTokens>
<processor type="YOUR_NAMESPACE.ResolveNameValueList, YOUR_ASSEMBLY" resolve="true" />
</resolveVariantTokens>
</pipelines>
</sitecore>
</configuration>
With such token, you only need to create a new Variant Token item and specify your custom token name:
This will give you:
Last note: Maybe this would be possible in NVelocity templates but do not go that path. If there is a different way (even if requires writing some code) to achieve something without NVelocty - go for it!