2016-04-13 76 views
0

在Umbraco中,我製作了一個字段(supportListItemWordMarking),用於輸入用戶希望在標題f.x中突出顯示的單詞的csv。在CSV中搜索單詞並用標記替換

This is a very fine header 

而且用戶希望有veryheader突出了紅色

然後一把umbraco現場看起來就像這樣:

非常頭

我試圖做一個剃刀腳本,以便它將在標題中查找輸入在supportListItemWordMarking字段中的字詞,然後輸出如下內容:

<h1>This is a <span class="red">very</span> fine <span class="red">header</span></h1> 

我想出了這一點:

@{ 
    if(subItem.HasValue("supportListItemWordMarking")) { 
     string[] wordMarking = subItem.GetValue("supportListItemWordMarking").ToString().Split(',');           
     } 
    } 

但我不知道這是正確的做法,所以我堅持。

回答

1

這可能是我會怎麼做:

var txt = "This is a very fine header"; 

var wordMarking = new string[] { "very", "header" }; 

// search for all words using regex 
var rx = new Regex(@"(\w+)", RegexOptions.Compiled); 

// the text to replace all regex matches with 
// any words found will be inserted into {0} using string.Format 
var replacementText = "<span class=\"red\">{0}</span>"; 

var newTxt = rx.Replace(txt, (match) => 
{ 
    var wordFound = match.Groups[1].Value; 

    // check if word should be marked 
    if (wordMarking.Contains(wordFound)) 
    { 
     // return the new word with the replacement 
     return string.Format(replacementText, wordFound); 
    } 

    return wordFound; 
}); 

如果列表wordMarking有很多的項目,那麼你應該使用字典來提高性能。

+0

謝謝!很好地工作! –