FreeMarker 基本指令 if list assign include

FTL 標(biāo)簽 (FreeMarker Template Language, FreeMarker模板的語(yǔ)言標(biāo)簽),也被成為指令。

if 指令
<#if condition>
    ...
</#if>
<#if condition>

<#else>
    ...
</#if>
<#if condition>
    ...
<#elseif condition>
    ...
<#else>
    ...
</#if>
list 指令

list指令的一般格式為: <#list sequence as loopVariable>repeatThis</#list>。
repeatThis 部分將會(huì)在給定的 sequence 遍歷時(shí)在每一項(xiàng)中重復(fù), 從第一項(xiàng)開(kāi)始,一個(gè)接著一個(gè)。
在所有的重復(fù)中, loopVariable 將持有當(dāng)前遍歷項(xiàng)的值。 這個(gè)變量?jī)H存在于 <#list ...> 和 </#list> 標(biāo)簽內(nèi)。

<#list misc.fruits as fruit>
<ul>
    <li>${fruit}</li>
</ul>
</#list>

等同

<#list misc.fruits>
<ul>
    <#item fruit>
     <li>${fruit}</li>
    </#fruit>
</ul>
</#list>
ist指令中<#sep></#sep>,存在下一項(xiàng)時(shí)執(zhí)行,即遍歷到數(shù)組的最后一項(xiàng)時(shí)將不會(huì)執(zhí)行。

以上指令(list, items, sep, else)可以聯(lián)合起來(lái)使用:

<#list misc.fruits>
  <p>Fruits:
  <ul>
    <#items as fruit>
      <li>${fruit}<#sep> and</#sep>
    </#items>
  </ul>
<#else>
  <p>We have no fruits.
</#list>
assign 指令

參考文檔

assign 指令可以 創(chuàng)建一個(gè)新的變量, 或者替換一個(gè)已經(jīng)存在的變量。注意僅僅頂級(jí)變量可以被創(chuàng)建/替換 (也就是說(shuō)你不能創(chuàng)建/替換 some_hash.subvar)。
assign 指令在命名空間中創(chuàng)建變量。通常它在當(dāng)前的命名空間 (也就是和標(biāo)簽所在模板關(guān)聯(lián)的命名空間)中創(chuàng)建變量。但如果你是用了 in namespacehash, 那么你可以用另外一個(gè) 命名空間 來(lái)創(chuàng)建/替換變量。

語(yǔ)法:<#assign name1=value1 name2=value2 ... nameN=valueN>

變量得創(chuàng)建可以是一個(gè)簡(jiǎn)寫的賦值操作符(從 FreeMarker 2.3.23 版本開(kāi)始): ++,--, +=,-=, *=,/= 或 %=。比如: <#assign x++> 和 <#assign x = x + 1> 是一樣的,并且 <#assign x += 2> 和 <#assign x = x + 2> 是相同的。 請(qǐng)注意, ++ 通常意味著算術(shù)加法 (對(duì)于非數(shù)字將會(huì)失敗),不像 + 或 += 可以進(jìn)行字符連接等重載操作。

<#assign seq = ["foo", "bar", "baz"]  x++ >
include 指令

include 指令在模板中插入其他文件的內(nèi)容

<#include "/copyright_footer.html">
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容