In this post I want to high­light the beauty of the Exter­nal­izer that is still unknown to a lot of developers.

Some­times in your CQ5 appli­ca­tion you want to get hold of the exter­nal url of a par­tic­u­lar page, for exam­ple if you want to spec­ify the url in your open­graph meta tag.

<meta property=“og:url” content=“http://mywebsite/myniceurl/mynicepage.html”/>

What you see quite often is this pattern:

<%
String exter­nalUrl = myPage.getPath() + “.html”;
%>
<meta property=“og:url” con­tent=”<%= exter­nalUrl %>”/>

This will result in some­thing like :

<meta property=“og:url” content=”/content/myinternalpath/myinternalpage.html”/>

This method doesn’t respect set­tings like, vanity-urls, resource map­pings, aliases, exter­nal host addresses.

What you should use is the Exter­nal­izer, that has meth­ods like .absoluteLink() and .relativeLink().

<%
Exter­nal­izer exter­nal­izer = bindings.getSling().getService(Externalizer.class);

String exter­nalUrl = externalizer.absoluteLink((SlingHttpServletRequest)request,
request.getScheme(), currentPage.getPath());
%>

This now results in the nice exter­nal url you want to share with your customers:

<meta property=“og:url” content=“http://mywebsite/myniceurl/mynicepage.html”/>

A very easy way to test this while being in devel­op­ment is to set an alias (Advanced-tab on Page prop­er­ties) on your page. You will see now that the alias is used in the exter­nal url, while your path remains the same.