Using functions in template scripts

Use templating functions in template scripts for common tasks such as navigating content. You typically pass arguments to a function and get an object in return. You can assign the returned object to a variable to process it further.

In this example we use the contentByPath function in a Freemarker script. We pass the path /hello to the function as an argument. At the path is a page named hello. The function returns a ContentMap object that represents the page node and its properties. We assign the ContentMap to the myPage variable. ContentMap provides easy access to a node's properties. We use the title method to retrieve the page title and render it on the page.

Configure the functions in a renderer

A renderer executes a template script and evaluates any templating functions in it. Every templating function must therefore be configured as a context attribute in the renderer.

In order to use your own templating functions with the default
FreemarkerRenderer, register the functions in the Freemarker renderer configuration. The Freemarker renderer is configured in /modules/rendering/renderers/freemarker.

Any module can register templating functions. Magnolia adds the functions to the Freemarker renderer configuration during module installation. When you add a module that registers functions to your webapp bundle, the functions become available to your template scripts.

Similarly, if you want to use standard Magnolia function sets such as cmsfn in your custom renderer, register them in your renderer configuration.

In this example, we assume the Site module is installed. We enable the custom function class MyCustomTemplatingFunctions in both freemarker and site renderers. Use
InstallRendererContextAttributeTask in the module version handler class of your custom module to add the function configuration to the renderers:

After module installation both renderers are configured with the custom functions.

Enable instantiation by IoC

Magnolia uses Dependency injection and inversion of control. Context attributes such as templating functions configured in a renderer are instantiated via IoC in the
RenderingContext. To enable instantiation, make sure your templating function class has a public constructor and register the class as a component in a module descriptor.