How can I override Sitecore <sc:Image>
control so that it reads the alt text from another field in the same item?
I want to be able to give a tag,
<sc:Image contextAltText="fieldName" ...>
and it should first look at this field and if empty, it should render the Media Item Alt
text as it normally does.
I don't need detailed implementation instructions. I only need to know which class and functions I have to overwrite.
You can create you own class inheriting from the Sitecore.Web.UI.WebControls.Image
and override it like this:
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]);
}
}
}
}
Maybe instead of calling parameters.Add
you will need to replace the original alt
value. I haven't tested the code so as you asked, it should only point you in the right direction.
EDIT: code below will not work with the ContentAltText
being field name instead of different alt text.
There is also another way, but I don't know if this will override default alt
value or this only works for new attributes:
<sc:Image runat="server" Field="Field Name" Parameters="alt=OverridenAltValue" />
EDIT 2:
To register your controls, find section below in web.config
and add your namespace with your custom prefix:
<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>
You may need to restart Visual Studio to make sure it recognizes new namespace.
Then use:
<msc:ImageWithAlt runat="server" ... />