天天看點

2021-2-15 FreeMarker基本指令表達式

FreeMarker學習

  • 基本指令
    • if指令
    • else if
        • list
    • include
  • 表達式

基本指令

if指令

<html>
<head>
  <title>Welcome!</title>
</head>
<body>
  <h1>
    Welcome ${user}<#if user == "Big Joe">, our beloved leader</#if>!
  </h1>
  <p>Our latest product:
  <a href="${latestProduct.url}">${latestProduct.name}</a>!
</body>
</html>
           

else if

<#if animals.python.price < animals.elephant.price>
  Pythons are cheaper than elephants today.
<#elseif animals.elephant.price < animals.python.price>
  Elephants are cheaper than pythons today.
<#else>
  Elephants and pythons cost the same today.
</#if>
           

list

<table border=1>
  <#list animals as animal>
    <tr><td>${animal.name}<td>${animal.price} Euros
  </#list>
</table>
           

效果

<p>We have these animals:
<table border=1>
    <tr><td>mouse<td>50 Euros
    <tr><td>elephant<td>5000 Euros
    <tr><td>python<td>4999 Euros
</table>
           

include

使用 include 指令, 我們可以在模闆中插入其他檔案的内容。

假設要在一些頁面中顯示版權聲明的資訊。那麼可以建立一個檔案來單獨包含這些版權聲明, 之後在需要它的地方插入即可。比方說,我們可以将版權資訊單獨存放在頁面檔案 copyright_footer.html 中:

<hr>
<i>
Copyright (c) 2000 <a href="http://www.acmee.com" target="_blank" rel="external nofollow"  target="_blank" rel="external nofollow" >Acmee Inc</a>,
<br>
All Rights Reserved.
</i>
當需要用到這個檔案時,可以使用 include 指令來插入:

<html>
<head>
  <title>Test page</title>
</head>
<body>
  <h1>Test page</h1>
  <p>Blah blah...
  <#include "/copyright_footer.html">
</body>
</html>
此時,輸出的内容為:

<html>
<head>
  <title>Test page</title>
</head>
<body>
  <h1>Test page</h1>
  <p>Blah blah...
<hr>
<i>
Copyright (c) 2000 <a href="http://www.acmee.com" target="_blank" rel="external nofollow"  target="_blank" rel="external nofollow" >Acmee Inc</a>,
<br>
All Rights Reserved.
</i>
</body>
</html>
當修改了 copyright_footer.html 檔案, 那麼通路者在所有頁面都會看到版權聲明的新内容。
           

表達式

快速浏覽(備忘單)
這裡給已經了解 FreeMarker 的人或有經驗的程式員的提個醒:

直接指定值
字元串: "Foo" 或者 'Foo' 或者 "It's \"quoted\"" 或者 'It\'s "quoted"' 或者 r"C:\raw\string"
數字: 123.45
布爾值: true, false
序列: ["foo", "bar", 123.45]; 值域: 0..9, 0..<10 (或 0..!10), 0..
哈希表: {"name":"green mouse", "price":150}
檢索變量
頂層變量: user
從哈希表中檢索資料: user.name, user["name"]
從序列中檢索資料: products[5]
特殊變量: .main
字元串操作
插值(或連接配接): "Hello ${user}!" (或 "Hello " + user + "!")
擷取一個字元: name[0]
字元串切分: 包含結尾: name[0..4],不包含結尾: name[0..<5],基于長度(寬容處理): name[0..*5],去除開頭: name[5..]
序列操作
連接配接: users + ["guest"]
序列切分:包含結尾: products[20..29], 不包含結尾: products[20..<30],基于長度(寬容處理): products[20..*10],去除開頭: products[20..]
哈希表操作
連接配接: passwords + { "joe": "secret42" }
算術運算: (x * 1.5 + 10) / 2 - y % 100
比較運算: x == y, x != y, x < y, x > y, x >= y, x <= y, x lt y, x lte y, x gt y, x gte y, 等等。。。。。。
邏輯操作: !registered && (firstVisit || fromEurope)
内建函數: name?upper_case, path?ensure_starts_with('/')
方法調用: repeat("What", 3)
處理不存在的值:
預設值: name!"unknown" 或者 (user.name)!"unknown" 或者 name! 或者 (user.name)!
檢測不存在的值: name?? 或者 (user.name)??
指派操作: =, +=, -=, *=, /=, %=, ++, --