You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Sitecore Experience Editor中带placeholder的Input渲染问题

解决Sitecore Experience Editor中Input Placeholder的渲染问题

这个问题我之前碰到过,核心原因是在Experience Editor模式下,@Html.Sitecore().Field()方法会输出包含Sitecore编辑控件的HTML代码(比如带scFieldEditable类的span标签),而input的placeholder属性只能接受纯文本内容,把HTML代码直接塞进去会导致浏览器解析错误,破坏DOM结构,就出现了你截图里的异常情况。

给你几个可行的解决方案:

方案1:使用FieldRenderer.GetFieldValue获取纯文本字段值

这是最简单直接的方法,GetFieldValue只会返回字段的纯文本内容,不会添加任何编辑相关的HTML标记,在编辑模式和正常模式下都能正常工作:

<div class="form-group">
  <input class="form-control" placeholder="@Sitecore.FieldRenderer.GetFieldValue(Sitecore.Context.Item, "Placeholder_Test")" value="123" />
</div>

方案2:直接读取字段原始值

如果你确认字段是纯文本类型,也可以直接读取Item的字段值,这种方式性能稍好,但要注意多语言和版本上下文的适配:

<div class="form-group">
  <input class="form-control" placeholder="@Sitecore.Context.Item["Placeholder_Test"]" value="123" />
</div>

方案3:保留编辑能力的进阶方案(可选)

如果需要在Experience Editor中仍然能编辑这个占位符字段,可以把字段放在页面的隐藏容器中,然后用JavaScript同步值到input的placeholder属性:

<div class="form-group">
  <!-- 隐藏的可编辑字段 -->
  <div style="display:none" class="scFieldEditable">@Html.Sitecore().Field("Placeholder_Test")</div>
  <input id="myInput" class="form-control" value="123" />
</div>

<script>
// 页面加载时同步字段值到placeholder
document.addEventListener('DOMContentLoaded', function() {
  const fieldValue = document.querySelector('.scFieldEditable').textContent.trim();
  document.getElementById('myInput').setAttribute('placeholder', fieldValue);
});

// 支持Experience Editor编辑后实时同步
if (typeof Sitecore !== 'undefined' && Sitecore.PageModes) {
  Sitecore.PageModes.PageEditor.on("item:updated", function() {
    const fieldValue = document.querySelector('.scFieldEditable').textContent.trim();
    document.getElementById('myInput').setAttribute('placeholder', fieldValue);
  });
}
</script>

以上方案中,方案1是最推荐的,既能解决渲染问题,又能保证字段值的正确获取(自动处理多语言、版本等上下文)。

内容的提问来源于stack exchange,提问作者Kun-Yao Wang

火山引擎 最新活动