1
votes

In AEM, content such as pages and images contains the '/content/' prefix in them. We are able to rewrite these url via Link Checker Transformer configuration and resourceResolver.map() method. URLs are being rewritten for HTML elements <a> and <form>.

But I want it to work for <img> elements as well.

I tried including the <img> elements to the Link Checker Transformer configuration by adding it to the 'Rewrite Elements' list as img:src:

enter image description here

I also checked the answers from What am I missing for this CQ5/AEM URL rewriting scenario? but both attempts didn't work for this issue.

Is there any way to do this?

1
have you configured the rewriter in /apps/XXX/config/rewriter ? - santiagozky
@santiagozky unfortunately no. i will read up on how to configure the rewriter through that. - khakiout
@santiagozky i tried it but nothing happens to <img> elements - khakiout

1 Answers

2
votes

Even if the rewriter and Link Checker Transformer didn't work. I used a custom LinkRewriter by using the Transformer and TransformerFactory interfaces. I based on the sample from Adobe for my code. I worked out something like this:

@Component(
     metatype = true,
     label = "Image Link Rewriter",
     description = "Maps the <img> elements src attributes"
)
@Service(value = TransformerFactory.class)
@Property(value = "global", propertyPrivate = true)
public class ImageLinkRewriter implements Transformer, TransformerFactory {

    // some variables

    public CustomLinkTransformer() {  }

    @Override
    public void init(ProcessingContext context,
                     ProcessingComponentConfiguration config) throws IOException {
        // initializations here
    }

    @Override
    public final Transformer createTransformer() {
        return new CustomLinkTransformer();
    }

    @Override
    public void startElement(String uri, String localName, 
                             String qName, Attributes atts) throws SAXException {
        if ("img".equalsIgnoreCase(localName)) {
            contentHandler.startElement(uri, localName, qName, rewriteImageLink(atts));
        }
    }

    private Attributes rewriteImageLink(Attributes attrs) {
        String attrName = "src";
        AttributesImpl result = new AttributesImpl(attrs);

        String link = attrs.getValue(attrName);
        String mappedLink = resource.getResourceResolver().map(request, link);

        result.setValue(result.getIndex(attrName), mappedLink);

        return result;
    }

}

Hope this helps others. Here are a few references: