FTL Basic Grammar

Keywords: FreeMarker encoding less Java

FTL Basic Grammar

Be careful:

With freemaker, all tags must be closed, otherwise freemaker will not be parsed.
freemaker comment: <# - comment content - > format section, not output.

1. Character output

${emp.name?if_exists}      // Variable exists, output the variable, otherwise no output
${emp.name!}            // Variable exists, output the variable, otherwise no output

${emp.name?default("xxx")}     // Variables do not exist, take the default value xxx 
${emp.name!"xxx"}          // Variables do not exist, take the default value xxx
//Common internal functions:

${"123<br>456"?html}      // HTML encoding of strings and escape of special characters in HTML
${"str"?cap_first}        // Capitalize the first letter of a string 
${"Str"?lower_case}        // Converting strings to lowercase 
${"Str"?upper_case}        // toUpperCase
${"str"?trim}              // Remove the blank characters before and after the string
//Two splicing methods for string splicing:

${"hello${emp.name!}"}     // Output hello + variable name
${"hello"+emp.name!}       // Use the + sign to connect and output the hello + variable name
//Substrings can be intercepted through the following grammar:

<#assign str = "abcdefghijklmn"/>

// Method 1
${str?substring(0,4)}  // Output abcd

// Method 2
${str[0]}${str[4]}    // The result is ae
${str[1..4]}        // The result is bcde

// Returns the index of the specified character

2. Date Output

${emp.date?string('yyyy-MM-dd')} //Date format

3. Digital Output (Take Digital 20 as an Example)

${emp.name?string.number} // / output 20
${emp.name?string.currency}    // ¥20.00 
${emp.name?string.percent}     // 20%
${1.222?int} // / Convert decimal to int, output 1

< #set number_format= "percent"/>// / Set the default number output mode ('percent', percentage)
< # assign answer = 42/> // declare variable answer 42
 # {answer} // Output 4,200%
${answer?string} // output 4,200%
${answer?string.number} // output 42
 ${answer?string.currency}// output 42.00
 ${answer?string.percent}// output 4,200%
# {answer} // output 42

Digital formatting interpolation can format numbers in the form of {expr;format}, where format can be:
mX: Minimum X-bit of decimal part
 MX: Maximum X-bit of decimal part
 The following examples are given:
<#assign x=2.582/>
<#assign y=4/>
# {x; M2}// Output 2.58
 # {y; M2}//Output 4
 # {x; m2}// Output 2.58
 # {y; m2}// Output 4.0
 # {x; m1M2}// Output 2.58
 # {x; m1M2}// Output 4.0

4. Declarative variables

<#Assign foo = false /> // / declare variables, insert Boolean values for display, and be careful not to use quotation marks
${foo?string("yes","no")} // Output "yes" when true, otherwise output "no"
//Several Ways to Declare Variables

<#assign name=value> 
<#assign name1=value1 name2=value2 ... nameN=valueN> 
<#assign same as above... in namespacehash>

<#assign name> 
  capture this 

<#assign name in namespacehash> 
capture this 


The comparison operators supported in expressions are as follows:
= Or=: Determine whether the two values are equal.
!=: Determine whether the two values are different.
> Or gt: Determine whether the left margin is greater than the right margin
 >= Or gt e: Determine whether the left-sided value is greater than or equal to the right-sided value
 <or lt: Determine whether the left margin is less than the right margin
 <= or lt e: Determine whether the left margin is less than or equal to the right margin

6. Arithmetic Operators

Arithmetic operations are fully supported in FreeMarker expressions.
FreeMarker supports arithmetic operators that include: +,-,*,/,% 
Be careful:
(1) Operators must have numbers on both sides
 (2) When using the + operator, if one side is a number and the other side is a string, the number will be automatically converted to a string and reconnected, such as: ${3+5"}, the result is: 35.

7. Logical Operators

The logical operators are as follows:
Logic and:&&
Logic or:||
Logical non:!

Logical operators can only act on Boolean values, otherwise errors will occur.

8. Operator priorities in FreeMarker are as follows (from high to low):

Univariate Operator:!
Built-in function:?
(3) Multiplication and division: *, /,%
(4) Addition and subtraction: -,+
(5) Comparison: >, <, >=, <=, <=, <= (lt, lte, gt, gte)
_, Equivalence: ==, =, =,!=
_. Logic and:&&
(1) Logic or:||
(2) Digital range:..

In fact, we should use parentheses to distinguish strictly in the development process, which is readable and error-free.

9. if logic judgment (note: elseif without spaces)

<#if condition>
<#elseif condition2>
<#elseif condition3>

if null value judgment

<! - When photoList is not empty - >
<#if photoList??>...</#if> 

<! -- It's worth noting that ${.} can only be used in text, not in expressions. The following code is incorrect: -->.
<#if ${isBig}>Wow!</#if>
<#if "${isBig}">Wow!</#if>

<! - Correct Writing - >
<#if isBig>Wow!</#if> 

10. switch (condition can be a number, can be a string)

<#switch value> 
<#case refValue1> 
<#case refValue2> 
<#case refValueN> 

11. Collection-Cycle

<!-- Ergodic set: -->
<#list empList! as emp> 

<!-- You can traverse collections like this: -->
<#list 0..(empList!?size-1) as i>

<!-- and jstl Cyclic similarity,You can also access the state of the loop. -->

empList?size    // Take the length of the set
emp_index:     // int type, the index value of the current object 
emp_has_next:     // boolean type, is there the next object

<!-- Use<#Brea > jump out of the loop - > break > break > break > break > break > break > break > break > break > jump out of the loop.
<#if emp_index = 0><#break></#if>

<!-- Set Length Judgment --> 
<#if empList?size != 0></#If > <! -- When judging = pay attention to only one = sign, not= - >.

<#Assignment L = 0.100/> <!--Defines a set of 0-100 of an int interval, and the range of numbers also supports inverse increment, such as 100.2->.
<#List 0.. 100 as I > <! - equivalent to Java for (int I = 0; I <= 100; I +) - - >

<!-- Intercept subsets: -->
empList[3..5] <!-- Return empList A subset of a set,The elements in a subset are empList The fourth in the set-6 Elements -->

<!-- Create a collection: -->
<#list ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] as x>

<!-- Set join operation,Connect two sets to a new set -->
<#list ["Monday", "Tuesday", "Wednesday"] + Thursday","Friday","Saturday","Sunday"] as x>

<!-- Besides,Collective elements can also be expressions,Examples are as follows: -->
[2 + 2, [1, 2, 3, 4], "whatnot"]

<!-- seq_contains: Judging the existence of elements in a sequence -->
<#assign x = ["red", 16, "blue", "cyan"]> 
${x?seq_contains("blue")?string("yes", "no")}    // yes
${x?seq_contains("yellow")?string("yes", "no")}  // no
${x?seq_contains(16)?string("yes", "no")}        // yes
${x?seq_contains("16")?string("yes", "no")}      // no

<!-- seq_index_of: The first index to appear -->
<#assign x = ["red", 16, "blue", "cyan", "blue"]> 
${x?seq_index_of("blue")}  <!-- 2 -->

<!-- sort_by: Sorting (ascending) -->
<#list movies?sort_by("showtime") as movie></#list>

<!-- sort_by: Sorting (descending) -->
<#list movies?sort_by("showtime")?reverse as movie></#list>

<!-- Specific introduction: -->
<!-- Unordered cases: -->
<#list movies as moive>
  <a href="${moive.url}">${moive.name}</a>

<!-- If sorting, use -->
<#list movies?sort as movie>
  <a href="${movie.url}">${movie.name}</a>

<!-- This is sorted by the initials of the elements. If you want to press list For sorting an attribute of an object element, use -->
<#list moives?sort_by(["name"]) as movie>
  <a href="${movie.url}">${movie.name}</a>

<!-- This is according to list Object element[name]Property sorting is ascending, and if descending is required, it is as follows: -->
<#list movies?sort_by(["name"])?reverse as movie>
  <a href="${movie.url}">${movie.name}</a>

12. Map objects

<!-- Establish map -->
<#assign scores = {Chinese": 86,"Mathematics": 78}>

<!-- Map concatenation operator -->
<#assign scores = {Chinese": 86,"Mathematics": 78} + {Mathematics": 87, "Java": 93}>

<!-- Map Element output -->
emp.name       // All use point grammar
emp["name"]    // Use brackets

FreeMarker supports the following escape characters:

\ ": Double quotation marks (u0022)
': Single quotation mark (u0027)
\ Backslash (u005C)
\ n: Line break (u000A)
\ r: Enter (u000D)
\t : Tab(u0009)
\ b: Backspace key (u0008)
\f : Form feed(u000C)
\l : <
\g : >
\a : &
\{ : {
\ xCode: The Unicode code code is specified directly by a 4-bit hexadecimal number, and the corresponding characters of the Unicode code code are output.

If a paragraph of text contains a large number of special symbols, FreeMarker provides another special format: you can add r tags before quotation marks for the specified string content, and the files after r tags will be output directly. See the following code:
${r'${foo}} // Output ${foo}
${r"C:/foo/bar"}// Output C:/foo/bar

14. include directive

// The include instruction acts like the JSP's include instruction:
<#include "/test.ftl" encoding="UTF-8" parse=true>

// In the above grammatical format, the two parameters are explained as follows:
encoding="GBK"  // Coding format
parse=true    // Whether it is parsed as ftl grammar, the default is true, false is introduced as text. Note: Boolean values in ftl files are directly assigned such as parse=true, rather than parse="true"

15. import directives

// Similar to import in jsp, it imports files and then uses macro components imported into files in current files
<#import "/libs/mylib.ftl" as my>
// The above code imports all the variables in the / lib/common.ftl template file and places them in a Map object called com. my is called namespace in freemarker.

16. compress compression

// Used to compress blank space and blank lines 

17. Special labels

<#T>//Remove left and right blanks and return lanes 

<#Lt >// Remove left margin and return lane change 

<#RT >// Remove the right margin and change lanes 

<#NT >// Cancel the above effect

18. escape,noescape encodes strings in HTML

// The escape instruction causes the interpolation of the body area to be automatically added with the escape expression, but it does not affect the interpolation in the string, but only the interpolation in the body. The grammatical format of the escape instruction is as follows:
<#escape x as x?html> 
  First name: ${firstName} 
<#noescape>Last name: ${lastName}</#noescape> 
  Maiden name: ${maidenName} 

// Same expression
First name: ${firstName?html} 
Last name: ${lastName} 
Maiden name: ${maidenName?html}

Posted by jerr0 on Tue, 20 Aug 2019 01:08:37 -0700