Templating functions

Templating functions perform typical templating tasks such as creating links and navigating content. This page explains where you can use templating functions and how to create your own.

Function sets

Templating functions are grouped into sets according to their purpose:

Function set Purpose Installed by module Version note

cmsfn

Navigate content and create links.

Templating (Available in every bundle.)

damfn

Get assets and renditions and create links to assets.

DAM (Digital Asset Management)

2.0+

sitefn

Get sites and themes.

Site

1.0+

navfn

Create site navigation.

MTE (Magnolia Templating Essentials)

0.14+

catfn

Get categories (tags) and access content by category.

Categorization

2.4+

searchfn

Search pages and content.

MTE (Magnolia Templating Essentials)

0.6+

restfn

Access REST clients.

REST Client

1.0.4+

imgfn

Get links to images from any workspace.

Imaging

3.2+

resfn

Create links to css and js files by given patterns.

Resources

2.5.1+

jsonfn

Generate JSON from JCR nodes of any workspace.

magnolia-jsonfn

tagfn

Search tagged content and tags.

Content Tags

1.0+

solrfn

Construct search queries and trigger searching in a Solr server.

Solr

5.6+

Templating function is not available?

  • Check that the module that includes the function set is installed.

  • Check that the functions are configured in the renderer, especially if you have a custom renderer.

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.

Example: Getting a page title with the cmsfn.contentByPath function

[#assign myPage = cmsfn.contentByPath("/hello")]
<p>
  ${myPage.title}
</p>

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.

See the function sets for more examples.

Using functions in Java classes

You can also use templating functions in Java classes. This is useful when you write your own templating functions or want to use the existing functions in a model class.

Example: Injecting TemplatingFunctions into a model class and creating a link to the site root page

public class ExampleModel<RD extends TemplateDefinition> extends RenderingModelImpl<TemplateDefinition> {
   private final TemplatingFunctions templatingFunctions;

    @Inject
    public ExampleModel(Node content, TemplateDefinition definition, RenderingModel<?> parent, TemplatingFunctions templatingFunctions) {
        super(content, definition, parent);
        this.templatingFunctions = templatingFunctions;
    }

    public String getLinkToRootPage() throws RepositoryException {
        Node rootPageNode = templatingFunctions.root(getNode());
        return templatingFunctions.link(rootPageNode);
    }
}

Notes:

  • Line 5: Inject a TemplatingFunctions object in the constructor. All Magnolia templating functions can be injected. WARNING: Never instantiate a templating function class directly.

  • Lines 11-12: Use the instance in the methods.

Creating custom templating functions

To create custom templating functions:

Implement a templating function class

This example introduces a custom function set examplesfn. It provides a function getRandomNumber which returns a random integer.

public class MyCustomTemplatingFunctions {

    public static final String examplesFunctionsName = "examplesfn";
    private Random random;

    public MyCustomTemplatingFunctions(){
        random = new Random();
    }

    /**
     * Returns a random Integer in the range of given min and max value.
     */
    public Integer getRandomNumber(int min, int max){
        int randomNum = random.nextInt((max - min) + 1) + min;
        return randomNum;
    }
}

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 info.magnolia.rendering.renderer.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 info.magnolia.rendering.module.setup.InstallRendererContextAttributeTask in the module version handler class of your custom module to add the function configuration to the renderers:

public class TemplatingExamplesModuleVersionHandler extends DefaultModuleVersionHandler {
    @Override
    protected List<Task> getExtraInstallTasks(InstallContext installContext) {
        List<Task> extraInstallTasks = new ArrayList<Task>(super.getExtraInstallTasks(installContext));
        extraInstallTasks.addAll(getFunctionsInstallerTask());
        return extraInstallTasks;
    }

    private List<Task> getFunctionsInstallerTask() {
        List<Task> tasks = new ArrayList<>();
        tasks.add(new InstallRendererContextAttributeTask("rendering", "freemarker", MyCustomTemplatingFunctions.examplesFunctionsName, MyCustomTemplatingFunctions.class.getName()));
        tasks.add(new InstallRendererContextAttributeTask("site", "site", MyCustomTemplatingFunctions.examplesFunctionsName, MyCustomTemplatingFunctions.class.getName()));
        return tasks;
    }

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

Renderers configured with custom functions on freemarker Renderers configured with custom functions on site

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 info.magnolia.rendering.context.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.

Module descriptor
<!DOCTYPE module SYSTEM "module.dtd" >
<module>
  <name>documentation-templating-examples</name>
  <displayName>Documentation templatingexamples</displayName>
  <versionHandler>info.magnolia.documentation.templating.setup.TemplatingExamplesModuleVersionHandler</versionHandler>
  <version>${project.version}</version>
  <components>
    <id>main</id>
    <component>
      <type>info.magnolia.documentation.templating.functions.MyCustomTemplatingFunctions</type>
      <implementation>info.magnolia.documentation.templating.functions.MyCustomTemplatingFunctions</implementation>
      <scope>singleton</scope>
    </component>
  </components>
  <dependencies>
    <dependency>
      <name>rendering</name>
      <version>5.4/*</version>
    </dependency>
    <dependency>
      <name>site</name>
      <version>1.0/*</version>
    </dependency>
  </dependencies>
</module>
Feedback

DX Core

×

Location

This widget lets you know where you are on the docs site.

You are currently perusing through the DX Core docs.

Main doc sections

DX Core Headless PaaS Legacy Cloud Incubator modules