覆盖sc:图像替代文字

时间:2015-10-15 10:17:09

标签: sitecore sitecore7 alt

如何覆盖Sitecore <sc:Image>控件,以便它从同一项目中的其他字段读取替代文字?

我希望能够提供标签,

<sc:Image contextAltText="fieldName" ...>

它应首先查看此字段,如果为空,则应该像往常一样呈现Media Item Alt文本。

我不需要详细的实施说明。我只需要知道我必须覆盖哪个类和函数。

1 个答案:

答案 0 :(得分:4)

您可以创建自己继承自Sitecore.Web.UI.WebControls.Image的类并按以下方式覆盖它:

namespace My.Assembly.Namespace
{
    public class MyImage : Sitecore.Web.UI.WebControls.Image
    {
        public virtual string ContentAltText { get; set; }

        protected override void PopulateParameters(Sitecore.Collections.SafeDictionary<string> parameters)
        {
            base.PopulateParameters(parameters);
            if (!String.IsNullOrEmpty(Item[ContentAltText] ))
            {
                parameters.Add("alt", Item[ContentAltText]);
            }
        }
    }
}

也许您不需要调用parameters.Add,而是需要替换原来的alt值。我没有按照你的要求测试代码,它应该只指向正确的方向。

编辑:以下代码无法使用ContentAltText字段名称而不是其他替代文字。

还有另一种方法,但我不知道这是否会覆盖默认的alt值,或者这仅适用于新属性:

<sc:Image runat="server" Field="Field Name" Parameters="alt=OverridenAltValue" />

编辑2

要注册您的控件,请在web.config中找到以下部分,并使用您的自定义前缀添加您的命名空间:

<system.web>
  <pages>
    <controls>
      <add tagPrefix="sc" namespace="Sitecore.Web.UI.WebControls" assembly="Sitecore.Kernel"/>
      <add tagPrefix="msc" namespace="My.Assembly.Namespace" assembly="My.Assembly"/>
      ...
    </controls>
  </pages>
</system.web>

您可能需要重新启动Visual Studio以确保它能够识别新的命名空间。

然后使用:

<msc:ImageWithAlt runat="server" ... />