cmsfn

cmsfn templating functions traverse the JCR repository, get content, and create links. Helper functions convert objects from one type to another.

This page only lists the most commonly used functions. See info.magnolia.templating.functions.TemplatingFunctions for the complete list.

Running the examples

The function examples on this page require sample content. Look at each example to figure out what kind of content it needs.

Example

Children is a function that retrieves the children of the current node. To get meaningful results, you need to execute the code on a page that has some children.

<ul>
[#list cmsfn.children(content, "mgnl:page") as child ]
    <li>${child.title!}</li>
[/#list]
</ul>

To create sample content:

  1. Put the code example into a page template script. You can use the hello.ftl script from the Hello Magnolia tutorial, for example.

  2. Create a page and assign the Hello template to it.

  3. Create some child pages and give them titles.

Your page structure could look like this:

Page structure

The animals page contains the example code. It has child pages and the children have titles. When you request the page the example code renders a list:

  • Cats

  • Dogs

  • Monkeys

Retrieving content

Content by path

Retrieves content by a given path from a workspace. The function retrieves content from the website workspace by default.

Method signature

ContentMap contentByPath(String path)

Arguments

Argument Description

path

required

The path where the content is stored.

workspace

optional, default is website

The workspace where the content map is stored. The function retrieves content from the website workspace by default.

Returns

ContentMap

Usage

cmsfn.contentByPath(path, workspace)

[#assign myResource = cmsfn.contentByPath("/sample-css/", "resources")]
${myResource.text!}
  • Node nodeByPath(String path, String workspace). Retrieves a node by a given path from a workspace.

Content by ID

Retrieves content by ID from a workspace. The function retrieves content from the website workspace by default.

Method signature

ContentMap contentById(String id, String workspace)

Arguments

Argument Description

id

required

The identifier whose content map you want to get.

workspace

optional, default is website

The workspace where the content map is stored. The function retrieves content from the website workspace by default.

Returns

ContentMap

Usage

cmsfn.contentById(id, workspace)

[#assign myResource = cmsfn.contentById("79fca5a6-b104-417b-a107-25b94ebc3961", "resources")]
[#if myResource??]
    ${myResource.text!}
[/#if]
  • Node nodeById(String id, String workspace). Retrieves a node by ID from a workspace.

  • Node getReferencedContent(Node content, String idPropertyName, String referencedWorkspace). Retrieves referenced content by a given content node, workspace and property. The content node you pass to this function must contain a property whose value identifies the referenced content.

Content by template ID

Find content objects by given template ID, below a given search root. Use this function to find pages that use a particular template, to aggregate content from similar pages, or to check where a template is used before deleting it from the system. You can limit the results to a set number, and add AND and ORDER BY parameters in SQL syntax.

Method signature

List<Node> contentListByTemplateId(Node searchRoot, String templateId)

List<Node> contentListByTemplateId(Node searchRoot, String templateId, int maxResultSize, String andClause, String orderByClause)

Arguments

Argument Description

searchRoot

required

The node to use as root for the search.

templateIds

required

The template IDs to search for.

maxResultSize

optional

Integer that sets the max number of results returned. This can significantly improve query performance.

andClause

optional

AND clause in SQL syntax excluding the word "AND" (for example, "date IS NOT NULL").

orderByClause

optional

ORDER BY clause in SQL syntax, excluding the words "ORDER BY" (for example, "date desc" or "date asc").

Returns

List<Node>

Usage

cmsfn.contentListByTemplateId(searchRoot, templateId)

cmsfn.contentListByTemplateId(searchRoot, templateId, maxResultSize, andClause, orderByClause)

Show the paths to all pages done with the template "hello"
[#assign currentNode = cmsfn.asJCRNode(content)]
[#assign rootPageNode = cmsfn.root(currentNode, "mgnl:page")!]
[#if rootPageNode??]
    [#assign helloPages=cmsfn.contentListByTemplateId(rootPageNode, "hello-magnolia:pages/hello")]
    [#if helloPages??]
        <ul>
        [#list helloPages as child ]
            <li>${cmsfn.asContentMap(child).title!}</li>
        [/#list]
        </ul>
    [/#if]
[/#if]
  • List<Node> contentListByTemplateIds(Node searchRoot, Set<String> templateIds, int maxResultSize, String andClause, String orderByClause). Retrieves content by a list of template IDs. This function takes many template IDs instead of only one.

Page by content

Retrieves the page that the passed content belongs to. For example, when you pass the content of a component to this function you get the parent page back. If the passed content has no parent page, which is the case for content managed in a content app and stored outside the website workspace, null is returned. If the passed content represents a page, then the passed content is returned.

Method signature

ContentMap page(ContentMap content)

Arguments

Argument Description

content

required

The content map whose page you want to find.

Returns

ContentMap

Usage

cmsfn.page(content)

[#assign pageNode = cmsfn.page(content)!"unknown"]
The title of the page node is ${pageNode.title}
  • Node page(Node content). Same as above but takes a node as an argument instead of a content map.

Inheritance

The methods here related to node inheritance .

The inherit methods are seldom necessary because areas already support inheritance natively through configuration.

Inherit components or properties

Wraps the provided node with an inheritance wrapper so that the node inherits the components and/or properties that exist in the equivalent ancestor nodes of the of the provided node’s anchor . This is typically the page node for the provided node.

Inheritance is subject to the inheritance configuration of the node, but can be overridden with the parameters of this method.

Method signature

Node inherit(Node content, String relPath, String nodeTypes, String nodeInheritance, String propertyInheritance)

Arguments

Argument Description

content

The node you want to inherit.

relPath

String

If not blank, the node will inherit the node specified by this relative path rather than the actual provided node.

This can be used to grab a specific property from a subnode.

nodeTypes

String

If not blank, only ancestors of the anchor with one of the nodeTypes in this comma delimited string are evaluated.

nodeInheritance

String

Specifies which child components of the ancestors to inherit.

propertyInheritance

String

Specifies which properties of the ancestors to inherit.

Returns

inheritedNode

Usage

cmsfn.inherit(content, relPath, nodeTypes, nodeInheritance, propertyInheritance)

Check if Node is inherited

Checks whether the Node is inherited from another Node or not.

Method signature

boolean isInherited(Node content)

Arguments

Argument Description

content

The node you want to inherit.

Returns

  • true indicates the Node is inherited from another Node.

  • false indicates the Node is not inherited from another Node.

Usage

cmsfn.isInherited(content)

Creates a link to a given node.

Method signature

String link(ContentMap contentMap)

Arguments

Argument Description

contentMap

required

The node you want to link to, as a content map.

Returns

String

Usage

cmsfn.link(contentMap)

[#assign rootNode = cmsfn.contentByPath("/home")]
<a href="${cmsfn.link(rootNode)}">${rootNode.title!}</a>
  • String link(Node node)

  • String link(String workspace, String nodeIdentifier)

Creates an external link by using the property value of the given node.

Method signature

String externalLink(ContentMap content, String linkPropertyName)

Arguments

Argument Description

content

required

The node where the link property is stored.

linkPropertyName

required

The name of the property where the link reference is stored.

Returns

String

Usage

cmsfn.externalLink(content, linkPropertyName)

[#assign externalLink = cmsfn.externalLink(content, "linkTypeExternal")!]
[#if externalLink??]
    <a href="${externalLink}">external link</a>
[/#if]
  • String externalLink(Node content, String linkPropertyName)

Returns the title for a link using the property values of the given node. If the linkTitlePropertyName property is null, the method falls back to the same method with 2 parameters, hence returning the link.

Method signature

String externalLinkTitle(ContentMap content, String linkPropertyName, String linkTitlePropertyName)

Arguments

Argument Description

content

required

The node where the link property is stored.

linkPropertyName

required

The name of the property where the link reference is stored.

linkTitlePropertyName

required

The name of the property where the title is stored.

Returns

String

Usage

cmsfn.externalLink(content, linkPropertyName, linkTitlePropertyName)

[#assign linkText = cmsfn.externalLinkTitle(cmsfn.decode(content), "linkTypeExternal", "title")!]
  • String externalLink(Node content, String linkPropertyName, linkTitlePropertyName)

Gets the link prefix by a given node. For instance, the result is /<contextPath> or something more complex if there is a URI2Repository mapping for the given node.

Method signature

String linkPrefix(Node content)

Arguments

Argument Description

content

required

The node you want to get the link prefix for.

Returns

String

Usage

cmsfn.linkPrefix(content)

[#assign prefix = cmsfn.linkPrefix(cmsfn.asJCRNode(content))!""]
prefix = ${prefix}

Returns a map of localized links to the current node. This means if you have defined three locales (en, de_DE and de_CH), the function returns localized links to the node of the context to which you are applying the function (if the current content node is a component, the function searches the parent page node).

Example

The map could look like this:

Key Value

en

/magnoliaAuthor/travel/about.html

de_DE

/magnoliaAuthor/de_DE/travel/about.html

de_CH

/magnoliaAuthor/de_CH/travel/about.html

Method signature

public Map<String, String> localizedLinks()

Returns

Map<String, String>

Usage

cmsfn.localizedLinks()

[#-- Build language navigation. --]
[#assign localizedLinks = cmsfn.localizedLinks()!]
[#if localizedLinks?has_content]
   [#assign languages = localizedLinks?keys]
   <ul>
      [#list languages as lang]
      [#assign current = cmsfn.isCurrentLocale(lang)]
      [#-- Use "compress" to put "li" and "a" on one line to prevent white spaces. --]
      <li>[@compress single_line=true]
         [#-- Current locale should not be linked. --]
         [#if current]${lang!}[/#if]
         [#if !current]<a href="${localizedLinks[lang]!'#'}">${lang!}</a>[/#if]
      [/@compress]</li>
      [/#list]
   </ul>
[/#if]

Converting nodes and content maps

Convert node to content map

Converts a node to a content map.

Method signature

ContentMap asContentMap(Node content)

Arguments

Argument Description

content

required

The node you want to convert.

Returns

ContentMap

Usage

cmsfn.asContentMap(content)

[#assign myNode = cmsfn.nodeByPath("/hello")]
[#assign myMap = cmsfn.asContentMap(myNode)]
${myMap.title!}

Convert node collection to content map list

Converts a collection of nodes to a list of content map items

Method signature

List<ContentMap> asContentMapList(Collection<Node> nodeList)

Arguments

Argument Description

nodeList

required

The node collection you want to convert to a content map list.

Returns

List<ContentMap>

Usage

cmsfn.asContentMapList(nodeList)

[#assign currentNode = cmsfn.asJCRNode(content)]
[#assign childrenNodesAsContentMaps = cmsfn.asContentMapList(cmsfn.children(currentNode, "mgnl:page"))]
<ul>
  [#list childrenNodesAsContentMaps as child ]
    <li>${child.title!}</li>
  [/#list]
</ul>

Convert content map to node

Converts a content map to a node.

Method signature

Node asJCRNode(ContentMap contentMap)

Arguments

Argument Description

contentMap

required

The content map you want to convert.

Returns

Node

Usage

cmsfn.asJCRNode(contentMap)

[#assign myNode = cmsfn.nodeByPath("/hello")]
[#assign myMap = cmsfn.asContentMap(myNode)]
${myMap.title!}

Convert content map collection to node list

Converts a content map collection to a list of nodes.

Method signature

List<Node> asNodeList(Collection<ContentMap> contentMapList)

Arguments

Argument Description

contentMapList

required

The content map collection you want to convert to a list of nodes.

Returns

List<Node>

Usage

cmsfn.asNodeList(contentMapList)

[#assign myMapList = cmsfn.children(content, "mgnl:page")]
<ul>
[#list cmsfn.asNodeList(myMapList) as child]
  <li>${cmsfn.parent(child)!}</li>
[/#list]
</ul>

Traversing JCR hierarchy

Children

Retrieves all the children (direct descendants) of the given node. If you don’t specify nodeType, the function will return all types of nodes, which is probably not what you want. A page typically has at least two kinds of child nodes: areas and pages. If you want just the pages, specify the node type mgnl:page.

Method signature

List<ContentMap> children(ContentMap content, String nodeTypeName, String blockIntermediateNodeName)

The blockIntermediateNodeName option is provided by the Content Editor module version 2.1 or higher.

To use the parameter, you need to use the content-editor-freemarker renderer.

Arguments

Argument Description

content

required

The node whose children you want to get.

nodeTypeName

optional

Type of the expected return nodes.

blockIntermediateNodeName

optional

The property allows you to access content of the intermediate block nodes.

In the Magnolia webapps, the name of the intermediate node is block.

Returns

List<ContentMap>

Usage

cmsfn.children(content, nodeTypeName)

<ul>
[#list cmsfn.children(content, "mgnl:page") as child ]
    <li>${child.title!}</li>
[/#list]
</ul>
  • List<Node> children(Node content)

  • List<Node> children(Node content, String nodeTypeName)

Ancestors

Retrieves the ancestors of a content map. You can specify nodeType to limit the types returned. If you do not, all node types are returned.

Method signature

List<ContentMap> ancestors(ContentMap contentMap)

List<ContentMap> ancestors(ContentMap contentMap, String nodeTypeName)

Arguments

Argument Description

content

required

The content map whose ancestors you want to get.

nodeTypeName

optional

Type of the expected return content map items.

Returns

List<ContentMap>

Usage

cmsfn.ancestors(contentMap, nodeTypeName)

Ancestor pages:
<ul>
[#list cmsfn.ancestors(content, "mgnl:page") as ancestor ]
  <li>${ancestor.title!}</li>
[/#list]
</ul>
  • List<Node> ancestors(Node content)

  • List<Node> ancestors(Node content, String nodeTypeName)

Parent

Retrieves the parent of a content map. You can specify nodeType to limit the types returned. If you do not, all node types are returned.

Method signature

ContentMap parent(ContentMap contentMap)

ContentMap parent(ContentMap contentMap, String nodeTypeName)

Arguments

Argument Description

contentMap

required

The content map whose parent you want to get.

nodeTypeName

optional

Type of the expected return content map items.

Returns

ContentMap

Usage

cmsfn.parent(contentMap, nodeTypeName)

[#assign parent = cmsfn.parent(content, "mgnl:page")! ]
Parent: ${parent.title!}
  • Node parent(Node content, String nodeTypeName). Same as above but takes a node as an argument instead of a content map.

  • boolean isFromCurrentPage(ContentMap content). Checks if the passed content is from the current page.

Root

Retrieves the root content map of a content map. You can specify a nodeType to limit the types returned. If you do not, all types are returned.

Method signature

ContentMap root(ContentMap contentMap)

ContentMap root(ContentMap contentMap, String nodeTypeName)

Arguments

Argument Description

contentMap

required

The content map whose root you want to get.

nodeTypeName

optional

Type of the expected return content map items.

Returns

ContentMap

Usage

cmsfn.root(contentMap, nodeTypeName)

[#assign rootNode = cmsfn.root(content)! ]
[#assign rootPage = cmsfn.root(content, "mgnl:page")! ]
The root node title is ${rootNode.title!"not found"}<br/>
The root page title is ${rootPage.title!}
  • Node root(Node content)

  • Node root(Node content, String nodeTypeName)

Site root

Retrieves the site root node by a given content map. The site root content map is defined as the page node with template type DefaultTemplateTypes#HOME. If no ancestor page with this type is returned, the JCR workspace root is returned.

Method signature

ContentMap siteRoot(ContentMap content)

Arguments

Argument Description

content

required

Returns

ContentMap

Usage

cmsfn.siteRoot(content)

[#assign homeLink = cmsfn.link(cmsfn.siteRoot(content))!"/"]
  • Node siteRoot(Node content). Retrieves the site root by node.

Dumping an object’s structure and content hierarchy

Dump

Inspects the structure and content of the given object upto the given depth and outputs it either in plain text form or, optionally, in a simple HTML format.

Method signature

String dump(Object obj, int depth, boolean asHtml)

Arguments

Argument Description

obj

required

Specifies the object type to be inspected. The following objects are available in the default implementation of this inspector function:

  • null values

  • Scalars

  • Dates

  • Calendar

  • Arrays

  • Collections

  • Maps

  • ContentMaps

  • Nodes

  • Properties

  • Objects (this one describes only the object class to avoid generating huge hierarchies)

depth

optional, default is 3

Specifies the depth of the inspection.

asHtml

optional, default is false

Output into a simple HTML format.

Returns

String

Usage

cmsfn.dump(obj, depth, asHtml)

${cmsfn.dump(content, 5, true)} # Outputs the properties of the content object with the depth of 5 in HTML format.

System state helpers

Check for edit mode

Checks whether the content is requested in the page editor in edit mode on author instance.

Method signature

boolean isEditMode()

Returns

boolean

Usage

cmsfn.isEditMode()

[#if cmsfn.editMode]You are in the edit mode<br/>[/#if]
Is edit mode: ${cmsfn.isEditMode()?string}

Check for preview mode

Checks whether the content is requested in the page editor in preview mode. The check can be run either on the author instance or on the public instance.

Method signature

boolean isPreviewMode()

Returns

boolean

Usage

cmsfn.isPreviewMode()

[#if cmsfn.previewMode]you are in the preview mode<br/>[/#if]
is preview: ${cmsfn.isPreviewMode()?string}<br/>

Check for author instance

Checks whether content is requested on the author instance.

Method signature

boolean isAuthorInstance()

Returns

boolean

Usage

cmsfn.isAuthorInstance()

[#if cmsfn.authorInstance]you are on an author instance<br/>[/#if]
is author instance: ${cmsfn.isAuthorInstance()?string}<br/>

Check for public instance

Checks whether content is requested on the public instance.

Method signature

boolean isPublicInstance()

Returns

boolean

Usage

cmsfn.isPublicInstance()

[#if cmsfn.publicInstance]you are on an public instance<br/>[/#if]
is public instance: ${cmsfn.isPublicInstance()?string}<br/>

String manipulation

Decode HTML

Removes escaping of HTML on properties in a content map.

Text stored in the JCR is usually encoded. For instance, HTML tag brackets are stored as &gt; and &lt;. However, the rich text field stores some HTML that should be rendered as proper HTML and not as encoded text. In that case, use the decode method.

Method signature

ContentMap decode(ContentMap content)

Arguments

Argument Description

content

required

The content map you want to removing escaping of HTML for.

Returns

ContentMap

Usage

cmsfn.decode(content)

[#if content.text?has_content]
    ${cmsfn.decode(content).text}
[/#if]
  • Node decode(Node content). Removes escaping of HTML on properties in a node.

  • ContentMap encode(ContentMap content). Adds escaping of HTML on properties and changes line breaks into &lt;br/&gt; tags in a content map.

  • Node encode(Node content). Adds escaping of HTML on properties and changes line breaks into &lt;br/&gt; tags in a node.

Shorten string

Shortens a given string to a set length and adds the suffix " …​" (space followed by three periods). Use this function to create teasers. Get the main content of a target page, shorten it to 100 characters and render the shortened content in a teaser component.

Method signature

String abbreviateString(String stringToAbbreviate, int length)

Arguments

Argument Description

stringToAbbreviate

required

The string you want to abbreviate.

length

required

The number of characters to shorten to.

Returns

String

Usage

cmsfn.abbreviateString(stringToAbbreviate, length)

[#assign text = cmsfn.abbreviateString(text, 80)]
  • String abbreviateString(String stringToAbbreviate, int length, String suffix). Same as above but using a custom suffix such as "Read more".

Request

Query string and fragment

Retrieves the query string and fragment of a URL. Returns an empty string if none exists.

Method signature

String queryStringAndFragment(String url)

Arguments

Argument Description

url

required

The URL whose query and fragment you want to get.

Returns

String

Usage

cmsfn.queryStringAndFragment(url)

[#assign queryStringAndFragment = cmsfn.queryStringAndFragment("http://example.com#myApp::running?q=abcd")]
Query string and fragment: ${queryStringAndFragment}

Language

See also Get localized links above.

Current language

Retrieves the language currently used.

Method signature

String language()

Returns

String

Usage

cmsfn.language()

<html xml:lang="${cmsfn.language()}" lang="${cmsfn.language()}" class="no-js">

${ctx.locale} is different from ${cmsfn.language()}, the former referring to the locale currently used by the user while the latter to the locale currently used by the site. See also AdminCentral and public locales.

Wrap content in i18n node wrapper

Wraps content in info.magnolia.jcr.wrapper.I18nNodeWrapper to deliver properties in a visitor’s language. Use this function only if required. Usually content nodes are already wrapped having localized properties if they exist. Explicit wrapping using this function might be required when retrieving from a custom model class which may deliver unwrapped content nodes.

Method signature

Node wrapForI18n(Node content)

Arguments

Argument Description

content

required

The content you want to wrap.

Returns

Node

Usage

cmsfn.wrapForI18n(content)

[#assign specialNode = cmsfn.wrapForI18n(model.specialNode)]

Test whether locale is current one

The function checks whether a given string representation of a locale is the same as the current locale. The current locale is the one selected by a user browsing the website (note that the current locale is not the same as the browser locale).

Method signature

boolean cmsfn.isCurrentLocale(String locale)

Returns

boolean

Arguments

Argument Description

locale

required

String representation of a locale.

Usage

cmsfn.isCurrentLocale("en")

[#if cmsfn.isCurrentLocale("en")] ... do something here ...[/#if]

Metadata

Retrieves content metadata such as the author and date last modified. This function returns a string representation of the metadata property. This means that when you ask for a date you don’t get a Date object back but a String.

Method signature

String metaData(ContentMap content, String property)

Arguments

Argument Description

content

required

The content map whose metadata you want to get.

property

required

Template ID Metadata property

mgnl:creationdate

mgnl:created

mgnl:lastmodified

mgnl:lastModified

mgnl:lastaction

mgnl:lastActivated

mgnl:authorid

mgnl:lastModifiedBy

mgnl:activatorid

mgnl:lastActivatedBy

mgnl:template

mgnl:template

mgnl:activated

mgnl:activationStatus

mgnl:comment

mgnl:comment

Returns

String

Usage

cmsfn.metaData(content, property)

This page was created by ${cmsfn.metaData(content, "mgnl:createdBy")!"nobody"}<br/>
and last modified ${cmsfn.metaData(content, "mgnl:lastModified")!"never"}
  • String metaData(Node content, String property). Same as above but takes a node as an argument instead of a content map.

File helpers

File extension

Tries to determine the file extension of a filename by returning the suffix after the last dot.

Method signature

String fileExtension(String fileName)

Arguments

Argument Description

fileName

required

The filename you want to get the extension for.

Returns

String

Usage

cmsfn.fileExtension(fileName)

[#assign fileName = "/lirum-larum.JPG"]
The extension of the file ${fileName} is "${cmsfn.fileExtension(fileName)}"

File size

Returns a friendly, human-readable file size such as 120 kB. Use this function, for example, to provide approximate sizes of downloadable files. See Apache FileUtils for more.

Method signature

String readableFileSize(long sizeBytes)

Arguments

Argument Description

sizeBytes

required

The specific number of bytes.

Returns

String

Usage

cmsfn.readableFileSize(sizeBytes)

[#assign fileSizeInBytes = 1321432216]
The size of my file is ${fileSizeInBytes}, this means: ${cmsfn.readableFileSize(fileSizeInBytes)}
Related topics
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