Page tree
Skip to end of metadata
Go to start of metadata

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  TemplatingFunctions  Javadoc 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:

 

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

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!}

Related functions

  • 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

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]

Related functions

  • 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

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??]
        [#list helloPages as child ]
            ${cmsfn.asContentMap(child).title!},
        [/#list]
    [/#if]
[/#if]

Related functions:

  • 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

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} 

Related functions

  • Node page(Node content). Same as above but takes a node as an argument instead of a content map.

Create link to a node

Creates a link to a given node.

Method signature

String link(ContentMap contentMap)

Arguments

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>

Related functions

  • String link(Node node)
  • String link(String workspace, String nodeIdentifier)

Create a link from a URL stored in a node

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

Method signature

String externalLink(ContentMap content, String linkPropertyName)

Arguments

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]

Related functions

  • String externalLink(Node content, String linkPropertyName)

Get the link title from a URL stored in a node

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

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")!]

Related functions

  • String externalLink(Node content, String linkPropertyName, linkTitlePropertyName)

Get link prefix by a node

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

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 on which you are applying the function. (If the current content node is a component, the function searches the parent page node.) (warning)  Magnolia 5.4.1+

Example: The map could look like this:

KeyValue
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

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

nodeList

required

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

Returns

List<ContentMap>

List of content map items.

Usage

cmsfn.asContentMapList(nodeList)

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

Convert content map to node

Converts a content map to a node.

Method signature

Node asJCRNode(ContentMap contentMap)

Arguments

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

contentMapList

required

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

Returns

List<Node>

List of nodes

Usage

cmsfn.asNodeList(contentMapList)

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

Traversing JCR hierarchy

Children

Retrieves all the children (direct descendants) of the given node. If you don't specify a 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 then specify the node type mgnl:page.

Method signature

List<ContentMap> children(ContentMap content)

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

Arguments

content

required

The node whose children you want to get.

nodeTypeName

optional

Type of the expected return nodes.

Returns

List<ContentMap>

A list of ContentMap items, in the case of the child nodes

Usage

cmsfn.children(content, nodeTypeName)

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

Related functions

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

Ancestors

Retrieves the ancestors of a content map. You can specify a nodeType to limit the types returned. If you don't all node types are returned.

Method signature

List<ContentMap> ancestors(ContentMap contentMap)

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

Arguments

content

required

The content map whose ancestors you want to get.

nodeTypeName

optional

Type of the expected return content map items.

Returns

List<ContentMap>

List of ContentMap items.

Usage

cmsfn.ancestors(contentMap, nodeTypeName)

Ancestor pages:
[#list cmsfn.ancestors(content, "mgnl:page") as ancestor ]
  ${ancestor.title!},
[/#list]

Related functions

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

Parent

Retrieves the parent of a content map. You can specify a nodeType to limit the types returned. If you don't all node types are returned.

Method signature

ContentMap parent(ContentMap contentMap).

ContentMap parent(ContentMap contentMap, String nodeTypeName)

Arguments

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!}

Related functions

  • 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 don't all types are returned.

Method signature

ContentMap root(ContentMap contentMap)

ContentMap root(ContentMap contentMap, String nodeTypeName)

Arguments

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!}

Related functions

  • 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

content

required

The content map whose root node you want to get.

Returns

ContentMap

Usage

cmsfn.siteRoot(content)

[#assign homeLink = cmsfn.link(cmsfn.siteRoot(content))!"/"]

Related functions:

  • 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

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(myObject, 5, true)} # Outputs myObject's properties to 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.

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.

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 brackets of HTML tags are stored as &gt; and &lt;. However, the Rich text field stores some HTML which should be rendered as proper HTML and not as encoded text. In such a case use the decode method.

Method signature

ContentMap decode(ContentMap content)

Arguments

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]

Related functions:

  • 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, dot, dot, dot). 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

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)]

Related functions:

  • 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

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

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">

Wrap content in i18n node wrapper

Wraps content into a 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

content

required

The content you want to wrap.

Returns

Node

Usage

cmsfn.wrapForI18n(content)

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

Testing whether a locale is the current

The functions checks whether a given String representation of a locale is equal to the current locale. The current locale is the one selected by a user browsing on the website. (Note that the current locale is not the same as the browser locale.) (warning) Magnolia 5.4.1+

Method signature

boolean cmsfn.isCurrentLocale(String locale)

Returns

boolean

Arguments

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

content

required

The content map whose metadata you want to get.

property

required

Metadata property:

  
CREATED"mgnl:created"
CREATED_BY"mgnl:createdBy"
LAST_MODIFIED"mgnl:lastModified"
LAST_MODIFIED_BY"mgnl:lastModifiedBy"
TEMPLATE"mgnl:template"
LAST_ACTIVATED"mgnl:lastActivated"
LAST_ACTIVATED_BY"mgnl:lastActivatedBy"
ACTIVATION_STATUS"mgnl:activationStatus"
DELETED"mgnl:deleted"
DELETED_BY"mgnl:deletedBy"
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"}

Related functions:

  • 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

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 to provide approximate sizes of downloadable files, for example. See Apache's FileUtils for more.

Method signature

String readableFileSize(long sizeBytes)

Arguments

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)}

1 Comment

  1. Is there a reason why there is no method like 

    cmsfn.link(path)

    ?

    Thanks for any hint