Search code examples
htmlfreemarkermagnolia

Get an absolute link from a relative one in Freemarker


I'm creating a site using Magnolia - CMS. Now I am implementing a blog page. On each blog page, there are several share buttons. Now I'm busy implementing the twittershare button. Here I am going to use the twitter cards. For that, I need to provide the URL of an image in a metatag. Main problem: I retreive my image like this: ${damfn.getAssetLink(content.blogImage)}. This only returns a relative path to my resource. Is there a quick way (in freemarker), that will convert tis to an absolute link?

Many thanks in advance!


Solution

  • usually you define magnolia.default.base.url in the magnolia.properties.

    then you can retrieve it with Components.getComponent(ServerConfiguration.class).getDefaultBaseUrl()

    now you have to install the service into freemarker. you can do that by adding installer-tasks into the renderers on startup. you do that in your module-version-handler. there you overwrite the getStartupTasks(...), something like this:

    @Override
    protected List<Task> getStartupTasks(InstallContext installContext) {
        final List<Task> tasks = new ArrayList<>();
        tasks.add(new InstallRendererContextAttributeTask("rendering", "freemarker", "serverConf", ServerConfiguration.class.getName()));
        tasks.add(new InstallRendererContextAttributeTask("site", "site", "serverConf", ServerConfiguration.class.getName()));
        return tasks;
    }
    

    now you can call in freemarker:

    "${serverConf.defaultBaseUrl}/${ctx.contextPath}/${damfn.getAssetLink(content.blogImage)}"
    

    checkout if the slashes are necesarry and make sure that defaultBaseUrl is set properly in your magnolia configuration ("/server/...")

    edit: there should be an easier by calling the current request in freemarker ${Request} so it could be something like "${Request.domain}/${ctx.contextPath}/${damfn.getAssetLink(content.blogImage)}" without injecting the serverConfiguration into the renderer