这里是一些使用FreeMarker语言的模板脚本编写样例。

基础知识

以下链接里的内容对FreeMarker初学者有帮助:

指令

关键的模板工具功能在Magnolia CMS标签库里,以指令(directives形式供使用。指令输入起来很快,却可以绘制复杂的输出。

标准FreeMarker指令

这里有一些最有用的FreeMarker指令及其样例代码:

if, else和elseif

支持常用运算符(&&, ||, !, ==, !=, >, <, >=, <=)。

布尔测试:

[#if content.header?has_content]
   <h1>${content.header}</h1>
[#else]
   DO_SOMETHING_ELSE
[/#if]
值比较:
[#if content.imageLocation == "top"]
   …
[/#if]
替换值:
[#if content.date?has_content]
   ${content.date?time?string.short}
[#elseif content.endDate?has_content]
   ${content.endDate?time?string.short}
[#else]
   No date is set!
[/#if]

list

可在任何Java集的扩展集合里进行迭代。

[#list model.getSomeList() as elem]
   <li>${elem.title!}</li>
[/#list] 

assign

assign允许您定义变量。任何非空对象都能传递给变量。

[#assign title = content.title!content.@name]
[#assign hasDate = content.date?has_content]
[#assign dateShort = content.date?time?string.short]
[#assign events = model.events]
[#assign stringgy = "Some direct string data"]

include

include指令包含一个FreeMarker模板脚本。

[#include "/templating-kit/templates/content/myScript.ftl"]

宏指令让您可以复用FreeMarker代码片段。参考STK > 模板 /templating-kit/components/macros里STK的使用例子。

[#macro test foo bar="Bar" baaz=-1]
    Test text, and the params: ${foo}, ${bar}, ${baaz}
[/#macro]
[@test foo="a" bar="b" baaz=5*5-2/]
[@test foo="a" bar="b"/]
[@test foo="a" baaz=5*5-2/]
[@test foo="a"/]

定制Magnolia指令

Magnolia CMS提供以下定制指令:

  • cms:init:嵌入了编辑页面需要的JavaScript和CSS。
  • cms:area用来绘制区域
  • cms:component用来绘制组件

对FreeMarker来说,这些指令都是由Directives类来完成的。这个类在配置应用的modules/rendering/renderers/freemarker/contextAttributes/cms/componentClass里配置。

对JSP,指令是由Templating JSP模块提供。

指令的语法随模板语言而略有不同。FreeMarker指令中,标准指令以“#”字符开头,而定制指令则以“@”符号开头。所有Magnolia cms标签库中的指令都以“@”开头,紧接着是标签库的名字,如cms,其次是一个点符号、宏的名字以及参数。在JSP里限制的字符则不同。

语法:

[@<tag library>.<macro> <parameter>=<value> /]

FreeMarker示例:绘制一个组件

[@cms.component content=component /]

JSP示例:绘制一个组件

<cms:component content="${component}"/>

cms:init

InitElement Java类嵌入了在编写实例上编辑页面所需的JavaScript和CSS。输出在HTML页面的head元件里。

示例:

[@cms.init /]

cms:area

cms:area指令AreaDirective)绘制区域以及里面的组件。编辑者可在区域内添加组件。可用的组件在区域定义里配置。

示例:

[@cms.area name="main"/]

该指令通过区域名称来引用区域。区域名称为包含区域定义的内容节点,如mainfooterstage

页面上的结果是一个区域栏、一个开始标记和一个结束标记。区域定义里title属性值在此区域栏里绘制。编辑者点击新建组件框的添加图标时,组件就添加到区域里了。

如果区域定义包含一个templateScript属性,那么由被引用的脚本绘制区域。如果脚本没有给出,则使用以下默认脚本:

区域类型为single

[@cms.component content=component /]

区域类型为list

[#list components as component]
   [@cms.component content=component /]
[/#list]

cms:component

cms:component指令(ComponentDirective)绘制组件content属性(attribute)定义组件编辑的内容,通常用在list指令里,在同一个map的组件里循环。

content属性传递要绘制的内容,或可能要编辑的内容(对于可编辑组件来说)。在编写实例上,指令绘制一个组件工具栏。组件定义里的title属性(property)值在工具栏中绘制。

属性(Attribute)描述缺省值
editable定义编辑图标是否应被显示,主要对继承的内容有用。cmsfn.isFromCurrentPage()
template要用到的组件定义名。节点里定义的模板。

示例:

[#list components as component ]
   [@cms.component content=component /]
[/#list]

常用指令属性

下列属性(attributes)可用任何指令传递,它们定义指令创建的元件应该工作在什么内容上。

属性描述缺省值
content一个节点或是内容地图。 
workspace指定路径时用到的工作区。与当前内容相同
path工作区中的路径。 

content属性

content属性告诉脚本它应该在哪个内容节点上操作。脚本通常在“当前”内容节点上操作。对于一个页面级脚本,当前节点为该页面;而对于一个区域级脚本,当前节点就是该区域。同样,对于一个组件级脚本,当前节点就是该组件。然后,也有一些情况,如您想要脚本在一个不同的内容节点上操作,这时content属性就变得方便实用。

例如,intro区域没有它自己的内容,也不包含任何组件,因为它是noComponent类型的。我们将通过使用content属性来实现让这个区域在页面内容上操作,编辑和绘制页面标题及摘要。

main.ftl脚本里,我们告诉main区域:“你应该在当前内容节点上操作,因为它是一个页面,而我是一个页面级脚本。”

<div id="wrapper-3">
    [@cms.area name="platform"/]
    [@cms.area name="main" content=content/]
    [@cms.area name="extras"/]
</div>

mainArea区域脚本里,我们再次传递相同的信息给intro区域:“你应该在当前内容节点上执行,它(仍然)是一个页面。”

<div id="main" role="main">
    [@cms.area name="breadcrumb" content=content/]
    [@cms.area name="intro" content=content/]
    [@cms.area name="opener"/]
    [@cms.area name="content"/]
</div><!-- end main -->

现在由intro区域编辑页面内容。尽管intro区域在页面上位于main区域的DIV元件里,标题和摘要实际上是属于页面的。它们是页面的而非区域的属性,所以应当将它们存放在内容结构里的页面节点下。

workspace属性

workspace属性(attribute)告知指令,内容在magnolia JCR库的哪个工作区。实际上,几乎总是website工作区;如果当前内容在website工作区里,则自动默认指向website。

指令绘制示例

这是一个关于指令在页面上如何绘制的例子。

  1. main脚本包含一个cms.init指令,嵌入了编写实例上所需的CSS和JavaScript。
  2. cms.area指令调用即将绘制的区域。该指令通过名字来辨认区域,在此例中为extras。如果该区域有子区域,您需要一个单独的脚本来调用要绘制的子区域。然而,如果该区域只包含组件,那么您不需要区域脚本。
  3. 页面的页脚同样使用cms.area指令来绘制。该区域不含子区域,只有组件。

添加您自己的指令

您可以添加自己的指令。执行以下步骤,可以使您自己的类中的Java方法和功能为模板脚本所用:

  1. 像通常一样写作和编译您的Java类。
  2. 拷贝这个类文件到您的Magnolia Web应用程序的WEB-INF/classes文件夹。
  3. 转到配置应用/modules/rendering/renderers/freemarker/contextAttributes
  4. /contextAttributes下,创建一个内容节点,如myClass。可以用类的用途命名。
  5. myClass里,创建两个数据节点:
    • componentClass,设置值为您放在WEB-INF/classes里的类的完全相称类名。
    • name,设置值为myClass

这样,您就能够使用${myClass.myMethod()} FreeMarker句法从模板获得myClass里所有的静态方法了。

模板功能

TemplatingFunctions包含了您可以在模板中可用的有用方法,这些方法以cmsfn出现。例如,decode方法可以从属性(properties)上移除HTML换码,下列代码片段展示了这个方法在stkTextImage组件脚本中的使用。

[#if content.text?has_content]
   ${cmsfn.decode(content).text}
[/#if]

DamTemplatingFunctions提供到Assets的直接权限以及定义有用的方法,这些方法以damfn出现。更多信息参考DAM模板工具。例如:

[#assign asset = damfn.getAssetForId(content.link)][#assign assetMap = damfn.getAssetMapForAssetId(content.link)]

STKTemplatingFunctions使附加的方法在STK模板里都可以使用,这些方法以stkfn出现。以下promos组件脚本片段包含了abbreviateString示例。

[#assign text = stkfn.abbreviateString(text, 80)]

每个绘制器的模板功能类在配置应用的/<module>/rendering/renderers/<renderer>/contextAttributes/<tag library>下配置。注意<tag library>内容节点和name数据的节点值与脚本里呈现方法的句法相匹配。

 

 

节点名

 
modules

 

 
rendering

 

 
renderers

 

 
freemarker

 

 
contextAttributes

 

 
cms

 

 
cmsfn

 

 
componentClass

info.magnolia.templating.functions.TemplatingFunctions

 
name

cmsfn

 
class

info.magnolia.rendering.renderer.FreemarkerRenderer

 
type

freemarker

 
jsp

 

 
listeners

 

 
version

5.0.2

 
standard-templating-kit

 

 
renderers

 

 
stk

 

 
contextAttributes

 

 
cms

 

 
cmsfn

 

 
stkfn

 

 
componentClass

info.magnolia.module.templatingkit.functions.STKTemplatingFunctions

 
name

stkfn

 
damfn

 

 
class

info.magnolia.module.templatingkit.renderers.STKRenderer

 

 

FreeMarker内建函数

FreeMarker提供一套强大的内建函数。它们可用作基本数据操作,不需要任何Java代码。内建函数在使用时前面加一个“?”字符。例如, ?exists用于检查一个值或对象是否存在,?has_content检查一个值或对象是否存在且为空。

字符串

大多数Java字符串在FreeMarker里都能实现并直接使用。例如:substringuncap_firstcapitalizedate,time,datetimeends_withhtmlindex_oflast_index_oflengthlower_caseupper_casecontainsreplacestarts_withtrim

布尔值

使用了布尔值的字符串将一个布尔值转化为一个字符串。您可以通过以下两种方法使用它:

  • foo?string使用默认字符来代表truefalse值,将布尔值转化为字符串。
  • foo?string(yes”,“no 在布尔值为真时返回第一个参数“yes”,否则,返回第二个参数“no”。

日期

日期内建函数有多种格式,例如:

[#assign microFormatDate = content.date?string("yyyy-MM-dd") + "T" + ontent.date?string("hh:mm:ss")]

专家级内建函数

还有一些专家级内建函数。最常用的有:

has_content决定HTML是否被绘制,以避免HTML标签。

[#if content.author?has_content]
 <p>
  <cite>${content.author}</cite>
 </p>
[/#if]

eval估算传递的FreeMarker代码。

[#assign indexString = ('"'+(ctx.indexString!)+'"')?eval]

Java对象

这些绘制上下文对象在AbstractRenderer及它的子类中设置:

content:当前的content节点。

${content.header!}

model:下面的样例代码对应模型类的getNavigation()方法。

${model.navigation!}

def:当前页面,区域或组件定义对象。

${def.headingLevel!}

ctx:参看WebContext

${ctx.user.name!}

state:参看AggregationState

${state.locale!}

检查null值

检查null值使您的模板更加稳定,因为FreeMarker遇到null值使会报告例外。检查有两种方法:

第一种方法是,使用“!”字符来提供缺省值,“!”后的内容被执行。

例如,下列代码想要从内容里分配title,如果不成功,它将返回到该内容节点名(name)。

<meta name="keywords" content="${content.keywords!content.title!content.@name}" />

您也可以指定值:

[#if content.keywordsEnabled!false]
     <meta name="keywords" content="${content.keywords!"These are some keywords"}" />
[/#if]

第二种方法是使用?has_content内建函数。下例在有值的情况下在h1标签里绘制header

[#if content.header?has_content]
     <h1>${content.header}</h1>
[/#if]

样例

这是最常用在您的模板脚本里的FreeMarker样例:

[#-- Accessing content --]
The value of "someProperty": ${content.someProperty}
Accessing a child node: ${content.childNode}
Accessing the child node collection: ${content?children}
Accessing the parent node: ${content?parent}
[#-- Special content properties --]
The content object is an instance of ContentMap and the following attributes are available:
The current node name: ${content.@name}
The current node path: ${content.@path}
The current node id: ${content.@id}
The current node depth: ${content.@depth}
The current node node type: ${content.@nodeType}

[#-- MetaData --]
The creation date: ${content.metaData.creationDate}
Metadata.modificationDate: ${content.metaData.modificationDate!" 
This node has never been modified."}

[#-- Component definition --]
The current component definition: ${def.name}
A component definition property: ${def.style}

[#-- Context: ctx --]
A request parmeter: ${ctx.myParam}
The current user name ${ctx.user.name} 
The current locale ${ctx.locale}

[#-- TemplatingFunctions: cmsfn--]
Create a link to a page: ${cmsfn.link(content)}
Create a binary link: ${cmsfn.link(content.image)}

[#-- Status based rendering --]
This is ${cmsfn.authorInstance?string('indeed', 'not')} an author instance.
This is ${cmsfn.editMode?string('indeed', 'not')} the edit mode.
This is ${cmsfn.previewMode?string('indeed', 'not')} the preview mode.

[#-- The Model executed before the paragraph rendering: model --]
The parent model: {model.parent}
The result of the execute method: ${actionResult}

[#-- AggregationState: state --]
Entry point of the rendering: ${state.mainContent}
Current content node: ${state.currentContent}
  • No labels