[英]replacing a variable text with other text in c#
我正在使用c#和sitecore在某些地方基本上使用令牌(请参阅: 如何在sitecore中创建自定义令牌 )。 我想我有一个解决方案,但是即使我没有收到任何错误,也不确定为什么它不起作用。
Item tokenItem = Sitecore.Context.Database.Items["/sitecore/content/Site Content/Tokens"];
if (tokenItem.HasChildren)
{
var sValue = args.FieldValue.ToString();
foreach (Item child in tokenItem.Children)
{
if (child.Template.Name == "Token")
{
string home = child.Fields["Title"].Value;
string hContent = child.Fields["Content"].Value;
if (sValue.Contains(home))
{
home.Replace(home, hContent);
}
}
}
}
home和hContent提取每个容器的正确值,但是在页面加载时,它仍在内容区域中输入了“ home”值(即@@ sales),而不是存储在hContent中的新值。 sValue包含所有内容(表,div,文本),我试图选出一个等于“ home”的值,然后用hContent替换“ home”值。 我想念什么?
您的代码实际上并没有做任何事情。 您似乎正在替换令牌项目字段本身( child.Fields["Title"]
和child.Fields["Content"]
)上的令牌,而不是输出内容流上的令牌。
请尝试以下操作,您需要将args设置为替换后的值,同时替换FirstPart
和LastPart
属性: 使用Sitecore ASP.NET CMS (在“未经测试的原型”链接中链接到代码) 替换富文本字段中的标记 。
我将重构您的代码以使其更容易:
public void Process(RenderFieldArgs args)
{
args.Result.FirstPart = this.Replace(args.Result.FirstPart);
args.Result.LastPart = this.Replace(args.Result.LastPart);
}
protected string Replace(string input)
{
Item tokenItem = Sitecore.Context.Database.Items["/sitecore/content/Site Content/Tokens"];
if (tokenItem.HasChildren)
{
foreach (Item child in tokenItem.Children)
{
if (child.Template.Name == "Token")
{
string home = child.Fields["Title"].Value;
string hContent = child.Fields["Content"].Value;
if (input.Contains(home))
{
return input.Replace(home, hContent);
}
}
}
}
return input;
}
这仍然不是最佳选择,但可以使您更接近。
如果将代码实现为RenderField管道的处理器,则需要将工作结果放回到args中。 尝试这样的事情:
Item tokenItem = Sitecore.Context.Database.Items["/sitecore/content/Site Content/Tokens"];
if (tokenItem.HasChildren)
{
var sValue = args.Result.FirstPart;
foreach (Item child in tokenItem.Children){
if (child.Template.Name == "Token") {
string home = child.Fields["Title"].Value;
string hContent = child.Fields["Content"].Value;
if (sValue.Contains(home)) {
sValue = sValue.Replace(home, hContent);
}
}
}
args.Result.FirstPart = sValue;
}
请注意,您需要确保在GetFieldValue处理器之后将此处理器修补到管道中。 该处理器负责将字段值拉入args.Result.FirstPart
。
好吧,您知道执行home.Replace(home, hContent);
时会发生什么吗home.Replace(home, hContent);
,它会通过替换的内容创建一个新的实例来什么是hContent
所以你需要做的是,这种情况下分配给一个新的变量或home
本身。 因此该代码段将如下所示:
if (sValue.Contains(home))
{
home = home.Replace(home, hContent);
}
你有没有尝试过:
home = home.Replace(home,hContent);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.