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>Copy
To create sample content:
Put the code example into a page template script. You can use the
hello.ftl script from the
Hello Magnolia
tutorial, for example.
Create a page and assign the Hello template to it.
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.
NodenodeById(String id, String workspace).
Retrieves a node by ID from a workspace.
NodegetReferencedContent(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.
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.
[#assign pageNode = cmsfn.page(content)!"unknown"]
The title of the page node is ${pageNode.title}
Copy
Related functions
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.
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.
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.
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]Copy
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
typemgnl:page.
[#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!}
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.
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.
Copy
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}
Copy
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/>
Copy
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/>
Copy
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/>
Copy
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 > and <. 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.
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 <br/> tags in a content
map.
Node encode(Node content). Adds escaping of HTML on properties and
changes line breaks into <br/> 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)
${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.
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]
Copy
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.
This page was created by ${cmsfn.metaData(content, "mgnl:createdBy")!"nobody"}<br/>
and last modified ${cmsfn.metaData(content, "mgnl:lastModified")!"never"}
Copy
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
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)}"
Copy
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)}