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 node
  • picker[type='image'] → restricts selection to image files
  • < 'jmix:image' → ensures the image node has standard image properties like j:height and j:width.

Displaying the image with automatic alt text

To display the image in your view, you need to:

  1. Retrieve the referenced node (imageNode).
  2. Build its public URL.
  3. Set the alt attribute dynamically. The simplest approach is to use getDisplayableName() on the image node
    1. If the jcr:title property is filled, it will be returned.
    2. If not, it falls back to the file name.

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 pixels
  • j: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 displayableName to populate the alt attribute automatically from the image title or file name.
  • Leverage j:height and j:width for better HTML output.