天天看點

freemarker 模闆引擎1.依賴2.模闆組成部分3.相關類4.常用指令5.例子6.常見錯誤

模闆引擎:根據模闆與綁定的資料,生成最終的xml文本。

java領域的表現層的三大模闆引擎——jsp,velocity,freemarker。jsp,java server page。

文本:直接輸出的部分

注釋:<#-- content -->

資料模型:${data.field}

freemarker.template.configuration

配置類。

freemarker.template.configuration.configuration(version incompatibleimprovements)

構造函數。

void freemarker.template.configuration.setdirectoryfortemplateloading(file dir)

設定存放模闆檔案(若幹個 xx.ftl)的目錄。

void freemarker.template.configuration.setdefaultencoding(string encoding)

設定編碼格式。

template freemarker.template.configuration.gettemplate(string name)

根據檔案名拿到template。

void freemarker.template.template.process(object datamodel, writer out)

有了模闆與資料,得到輸出,寫入out中。若想得到字元串,一般會傳入stringwriter。

for循環周遊的效果。

<#list fruits as fruit><br>

   <li>${fruit.name}<br>

</#list>

條件判斷。為真時,标簽對内的内容才會輸出。

<#--标簽内的屬性,不能用${}的形式-->

<#if isbig && isexpensive>wow!</#if>

<#-- 使用關系比較符時,可以直接用大于号,但要放在括号内,保證标簽閉合符号能被正确處理-->

<#if (x>y)>x is larger than y</#if>

<#-- 使用關系比較符時,也可以用-->

<#if (x  gt y)>x is larger than y</#if>

判斷某個變量是否存在

取得字元串長度

将數字轉為字元串

引入局部變量并指派

當用到了${object.x},但datamodel中沒有這個屬性,就會報下面這樣的錯誤。

解決辦法:使用<#if obj.x??>做判斷。