images
alt
Developer
Jahia 8
How to add an alternate text to an image in media and have it automatically added to an image component
Question
In Jahia, when I select an image from the media manager for my content, how can I ensure that the alt attribute in the <img> tag is automatically filled using the image’s title (or file name if no title is set)?
Answer
Understanding images in Jahia
In Jahia, an image is simply a file node stored in the JCR repository.
When you want to use an image inside a content definition, you reference it using a property of type weakreference and configure the picker to accept images only.
Example in your CND definition:
- image (weakreference, picker[type='image']) < 'jmix:image'
Here:
weakreference→ stores a reference to the image nodepicker[type='image']→ restricts selection to image files< 'jmix:image'→ ensures the image node has standard image properties likej:heightandj:width.
Displaying the image with automatic alt text
To display the image in your view, you need to:
- Retrieve the referenced node (
imageNode). - Build its public URL.
- Set the alt attribute dynamically. The simplest approach is to use
getDisplayableName()on the image node- If the
jcr:titleproperty is filled, it will be returned. - If not, it falls back to the file name.
- If the
Example in JSP:
<c:set var="imageNode" value="${currentNode.properties.image.node}"/>
<c:if test="${! empty imageNode}">
<c:url var="imageUrl" value="${imageNode.url}" context="/"/>
<c:set var="alt" value="${imageNode.displayableName}"/>
<img src="${imageUrl}" alt="${fn:escapeXml(alt)}" />
</c:if>
Additional image properties
When you use jmix:image, Jahia automatically adds standard image metadata to the node:
j:height→ Image height in pixelsj:width→ Image width in pixels
These can be used to:
- Set explicit width and height attributes in <img> tags.
- Implement responsive image handling.
Example:
width="${imageNode.properties['j:width'].string}"
height="${imageNode.properties['j:height'].string}"
Summary
- Use a weakreference property to link an image in your definition.
- Use
displayableNameto populate the alt attribute automatically from the image title or file name. - Leverage
j:heightandj:widthfor better HTML output.