如何使用 foreach 获取 "Name Value List" 类型字段的值?

how to take the value of a field of type "Name Value List" with a foreach?

(在 sitecore 上)我添加了一个类型为“Name Value List”的新字段(名为:Button); 现在,通过 foreach,我应该能够获取应该成为按钮的键的值。所有这些都必须替换以前由每个按钮的每个“if”组成的代码,即:

<div class="podcastsButtons__content">
             
    @if (!string.IsNullOrEmpty(tit.Category.SprekerURL))
    {
        <button class='podcastsBtn podcastsBtn--spreaker' data-url='@tit.Category.SprekerURL'>
            <span></span>
        </button>
    }
    @if (!string.IsNullOrEmpty(tit.Category.SpotifyURL))
    {
        <button class='podcastsBtn podcastsBtn--spotify' data-url='@tit.Category.SpotifyURL'>
            <span></span>
        </button>
    }
    @if (!string.IsNullOrEmpty(tit.Category.ApplePodcastURL))
    {
        <button class='podcastsBtn podcastsBtn--apple' data-url='@tit.Category.ApplePodcastURL'>
            <span></span>
        </button>
    }
    @if (!string.IsNullOrEmpty(tit.Category.GooglePodcastURL))
    {
        <button class='podcastsBtn podcastsBtn--google' data-url='@tit.Category.GooglePodcastURL'>
            <span></span>
        </button>

Sitecore 中“名称值列表”字段的内容在内部存储类似于查询字符串,即以原始格式 key1=value1&key2=value2

您可以使用例如 Sitecore.StringUtil.ParseNameValueCollection 手动解析字段值,但更简单的方法通常是像这样转换字段:

var field = (Sitecore.Data.Fields.NameValueListField) item.Fields["Button"];
foreach (var key in field.NameValues.AllKeys)
{
  var value = field.NameValues[key];
  // do something with key and value
}

值得注意的是,Sitecore 存在一些内部编码问题,因此无法在不导致内容损坏的情况下在“名称值列表”字段中正确表示所有字符。