FreeMarker-- usage of expressions and operators (comprehensive/with examples)

Original URL: FreeMarker--Usage of Expressions and Operators (Comprehensive/Examples)_IT Blog-CSDN Blog

Introduction

This article introduces the usage of expressions and operators of FreeMarker.

Expressions are the core functionality of FreeMarker. When an expression is placed in the interpolation syntax (${...}), it indicates that the value of the expression needs to be output. The expression syntax can also be combined with FreeMarker tags to control the output.

specify the value directly

a. String

${"我的文件保存在C:\\盘"} 
${'我名字是\"annlee\"'}

The output is:

我的文件保存在C:\盘 
我名字是"annlee"

FreeMarker supports the following escape characters:

  • \"; double quotes (u0022) 
  • \'; single quote (u0027) 
  • \\; Backslash (u005C) 
  • \n;Line feed (u000A) 
  • \r; Enter (u000D) 
  • \t;Tab(u0009) 
  • \b; Backspace key (u0008) 
  • \f;Form feed(u000C) 
  • \l;< 
  • \g;> 
  • \a;& 
  • \{;{ 
  • \xCode; Specify the Unicode code directly through the 4-digit hexadecimal number, and output the character corresponding to the Unicode code.

        If a certain text contains a large number of special symbols, FreeMarker provides another special format: you can add an r mark before the quotation mark of the specified string content, and the file after the r mark will be output directly. Look at the following code:

${r"${foo}"} 
${r"C:\foo\bar"}

The output is:

${foo} 
C:\foo\bar

b. Value

The value in the expression is output directly without quotation marks, the decimal point is separated by ".", and the grouping "," symbol cannot be used. FreeMarker does not yet support scientific notation, so "1E3" is wrong. The following points need to be paid attention to when using numerical values ​​in FreeMarker expressions:

  • The value cannot omit the 0 before the decimal point, so ".5" is wrong
  • Values ​​8 , +8 , 8.00 are all the same

c. Boolean value

Use true and false directly without quotes.

d. Date type
FreeMarker supports three types of date, time, and datetime. The values ​​of these three types cannot be specified directly, and usually need to be converted with the help of three built-in functions of date, time, and datetime.

<#assign test1 = "2009-01-22"?date("yyyy-MM-dd") />;
           <#assign test2 ="16:34:43"?time("HH:mm:ss") />
           <#assign test2 = "2009-01-22 17:23:45"?datetime("yyyy-MM-dd HH:mm:ss") />
           ${test1?string.full}

e. Collection

Sets are enclosed in square brackets, and each set element is separated by a comma ",", see the following example:

<#list ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期天"] as x> 
${x} 
</#list>

The output is:

星期一 
星期二 
星期三 
星期四 
星期五 
星期六 
星期天

In addition, collection elements can also be expressions, examples are as follows:

[2 + 2, [1, 2, 3, 4], "whatnot"]

        You can also use a range of numbers to define a set of numbers, such as 2..5 is equivalent to [2, 3, 4, 5], but it is more efficient. Note that there is no need to use square brackets when using a range of numbers to define a set, and the range of numbers also supports reverse Incrementing range of numbers, such as 5..2 

f. Map collection

Map objects are included in curly braces, the key-value pairs in the Map are separated by English colons ":", and multiple sets of key-value pairs are separated by English commas ",". The following is an example:

{"语文":78, "数学":80}

The key and value of the Map object are both expressions, but the key must be a string.

output variable value

        When FreeMarker's expression outputs variables, these variables can be top-level variables, variables in the Map object, or variables in the collection, and the dot (.) syntax can be used to access the properties of the Java object. These cases are discussed below

a. Top-level variables 

The so-called top-level variable is the value directly placed in the data model, for example, the following data model:

Map root = new HashMap();   //创建数据模型 
root.put("name","annlee");   //name是一个顶层变量

For top-level variables, directly use ${variableName} to output the variable value. The variable name can only be a combination of letters, numbers, underscores, $, @, and #, and cannot start with a number. In order to output the value of the above name, you can Use the following syntax:

${name}

b. Output collection elements 

        If you need to output the collection elements, you can output the collection elements according to the index of the collection elements. The index of the collection elements is specified in square brackets. Assuming that there are indexes: 

["星期一","星期二","星期三","星期四","星期五","星期六","星期天"]

The index name is week. If you need to output Wednesday, you can use the following syntax:

${week[2]}   //输出第三个集合元素

In addition, FreeMarker also supports returning a sub-collection of a collection. If you need to return a sub-collection of a collection, you can use the following syntax:

week[3..5]   //返回week集合的子集合,子集合中的元素是week集合中的第4-6个元素

c. Output Map elements 

        The Map object here can be an instance of a direct HashMap, or even a JavaBean instance. For a JavaBean instance, we can also regard it as a Map instance whose attribute is key and attribute value is value. To output the value of a Map element, either dot syntax or square bracket syntax can be used. Suppose you have the following data model:

Map root = new HashMap(); 
Book book = new Book(); 
Author author = new Author(); 
author.setName("annlee"); 
author.setAddress("gz"); 
book.setName("struts2"); 
book.setAuthor(author); 
root.put("info","struts"); 
root.put("book", book);

In order to access the author's name of a book called struts2 in the data model, the following syntax can be used:

book.author.name    //全部使用点语法 
book["author"].name 
book.author["name"]    //混合使用点语法和方括号语法 
book["author"]["name"]   //全部使用方括号语法

When using the dot syntax, variable names have the same restrictions as top-level variables, but the bracket syntax does not, because the name can be the result of any expression.

string manipulation

        FreeMarker's expression is very flexible for string operations, it can connect string constants and variables, and can also return substrings of strings, etc.

There are two syntaxes for string concatenation:

  1. Use ${..} or #{..} to insert the value of the expression in the string constant part to complete the string concatenation.
  2. Concatenate strings directly using the concatenation operator +

For example, the following data model:

Map root = new HashMap(); root.put("user","annlee");

The following connects the user variable with the constant:

${"hello, ${user}!"}   //使用第一种语法来连接 
${"hello, " + user + "!"} //使用+号来连接

The above output strings are hello, annlee!, it can be seen that the effects of the two grammars are exactly the same.

It is worth noting that ${..} can only be used in text parts and cannot be used in expressions. The following code is wrong:

<#if ${isBig}>Wow!</#if> 
<#if "${isBig}">Wow!</#if>

should be written as

<#if isBig>Wow!</#if>

The substring can be intercepted according to the index of the string. If only one index value is specified when intercepting the substring, it is used to obtain the character corresponding to the specified index in the string; if two index values ​​are specified, two indexes are returned. The string substring in the middle. If there is the following data model:

Map root = new HashMap(); root.put("book","struts2,freemarker");

Substrings can be intercepted by the following syntax:

${book[0]}${book[4]}   //结果是su 
${book[1..4]}     //结果是tru

set join operator

The set operator mentioned here is to connect two sets into a new set. The operator for connecting sets is +, see the following example:

<#list ["星期一","星期二","星期三"] + ["星期四","星期五","星期六","星期天"] as x> 
${x} 
</#list>

The output is:

星期一 星期二 星期三 星期四 星期五 星期六 星期天

Map join operator

        The connection operator of the Map object also connects two Map objects into a new Map object. The connection operator of the Map object is +. If the two Map objects have the same key, the value on the right replaces the value on the left. See the following example:

<#assign scores = {"语文":86,"数学":78} + {"数学":87,"Java":93}> 
语文成绩是${scores.语文} 
数学成绩是${scores.数学} 
Java成绩是${scores.Java}

The output is:

语文成绩是86 
数学成绩是87 
Java成绩是93

arithmetic operator

        Arithmetic operations are fully supported in FreeMarker expressions, and the arithmetic operators supported by FreeMarker include: +, -, *, /, % See the following code:

<#assign x=5> 
${ x * x - 100 } 
${ x /2 } 
${ 12 %10 }

The output is:

-75   2.5   2

There are a few things to keep in mind when using arithmetic operators in expressions: 

  1. The operands on either side of the operator must be numbers 
  2. When using the + operator, if one side is a number and the other side is a string, it will automatically convert the number to a string and then connect, such as: ${3 + "5"}, the result is: 35

Values ​​can be rounded using the built-in int function, such as:

<#assign x=5> 
${ (x/2)?int } 
${ 1.1?int } 
${ 1.999?int } 
${ -1.1?int } 
${ -1.999?int }

turn out:

2 1 1 -1 -1

comparison operator

The comparison operators supported in expressions are as follows:

  1. = or ==: Determines whether two values ​​are equal. 
  2. !=: Determine whether two values ​​are not equal. 
  3. >or gt: determine whether the value on the left is greater than the value on the right 
  4. >= or gte: determine whether the value on the left is greater than or equal to the value on the right 
  5. < or lt: determine whether the value on the left is smaller than the value on the right 
  6. <= or lte: determine whether the value on the left is less than or equal to the value on the right

Note: = and != can be used for strings, numbers and dates to compare whether they are equal, but both sides of = and != must be the same type of value, otherwise an error will occur, and FreeMarker is an exact comparison, "x", "x ", "X" are not equal. Other operators can act on numbers and dates, but not on strings. Most of the time, using gt and other letter operators instead of > will have a better effect , because FreeMarker will interpret > as the end character of the FTL tag , of course, you can also use brackets to avoid this situation, such as: <#if (x>y)>

Logical Operators

Logical operators are as follows:

Logical AND: && 
Logical OR: || 
Logical Not: !
Logical operators can only act on Boolean values, otherwise an error will occur

built-in function

        FreeMarker also provides some built-in functions to convert the output, you can follow any variable with ?, ? followed by a built-in function, you can use the built-in function to rotate the output variable. The following are commonly used built-in string functions:

  • html: HTML encodes a string 
  • cap_first: capitalize the first letter of the string 
  • lower_case: convert the string to lowercase 
  • upper_case: convert the string to uppercase 
  • trim: remove whitespace characters before and after the string

The following are commonly used built-in functions for collections

  • size: get the number of elements in the sequence

The following are commonly used built-in functions for numeric values

  • int: get the integer part of the number, the result is signed

For example:

<#assign test="Tom & Jerry"> 
${test?html} 
${test?upper_case?html}

turn out:

Tom &amp; Jerry   TOM &amp; JERRY

null handling operator

overview

        In FreeMarker, nonexistent variables and null are empty values.

        FreeMarker's handling of null values ​​is very strict. FreeMarker variables must have values, and variables that have not been assigned a value will throw an exception, because FreeMarker unassigned variables can force errors to prevent many potential errors, such as missing potential variable names, or Other variables are wrong.

To handle missing variables, FreeMarker provides two operators.

  • !: Specifies the default value for missing variables 
  • ??: Determine whether a variable exists

When using ! to specify a default value, the type of the default value is not required to be the same as the variable type.

Using the ?? operator is very simple, it always returns a Boolean value, the usage is: variable??, if the variable exists, return true, otherwise return false.

The ! operator can be used in the following two ways: 

  1. variable!
  2. variable!defaultValue

The first usage does not specify a default value for missing variables, indicating that the default value is an empty string, a collection of length 0, or a Map object of length 0.

The second usage assigns default values ​​to missing variables.

example

Determine whether it exists by using the exists keyword or the "??" operator

will return a boolean value

<#if user.name?exists>
 //TO DO
</#if>
 
<#if user.age??>
 //TO DO
</#if>
 

ignore null values

Assumption premise: user.name is null

  • ${user.name}
    • abnormal
  • ${user.name!}
    • display blank (empty string)
  • ${user.name!'vakin'}
    • If user.name is not empty, display its own value, otherwise display vakin
  • ${user.name?default('vakin')}
    • If user.name is not empty, display its own value, otherwise display vakin
  • ${user.name???string(user.name,'vakin')}
    • If user.name is not empty, display its own value, otherwise display vakin

With or without brackets

  • product.color??
    • Only test if color is null
  • 
(product.color)??
    • Test if product and color are null 


operator precedence

The operator precedence in FreeMarker is as follows (from high to low):

  • Unary operators: ! 
  • Built-in functions: ? 
  • Multiplication and division: *, / , % 
  • Addition and subtraction: - , + 
  • Comparisons: > , < , >= , <= (lt , lte , gt , gte)
  • Equality: == , = , != 
  • Logical AND: && 
  • Logical OR: || 

Guess you like

Origin blog.csdn.net/feiying0canglang/article/details/128139179
Recommended