Freemarker template, freemarker

Source: Internet
Author: User

Freemarker template, freemarker

1. Overall Structure

The template (FTL programming) is composed of the following parts:
Text: The Text is output as is.
Interpolation: This part of the output is replaced by the calculated value. Interpolation is separated by $ {And} (or # {And}. We do not recommend this style ).
FTL tags Tag: the FTL tag is similar to the HTML tag, but they give instructions to FreeMarker and are not printed in the output content.
Comments: FTL Comments are similar to HTML Comments, but they are separated by <# -- and -->. The comment will be ignored by FreeMarker, and will not be displayed in the output content.


2 commands

Use the FTL label to call the directives command, such as the list command.

There are two types of commands: pre-defined commands and user-defined commands. Use @ to replace user-defined commands #

The deeper difference is that if there is no nested content in the instruction, you must use <@ mydirective parameters/> this way, and the predefined value is <# directive something>.

FreeMarker can understand predefined commands without # (for example, <if user = "Big Joe">... </if> ). We do not recommend this.


3 expression
You can use variables or other complex expressions to provide values for interpolation or command parameters. For example, if we set x to 8 and y to 5, the value of (x + y)/2 will be processed as a numerical value of 6.5.

When values are provided for interpolation, the interpolation method is $ {expression}

When providing value for the command parameters: In the Getting Started section, we can see the use of the if command. The syntax of this command is: <# if expression>... </# if>. The expression calculation result must be boolean.


Quick browsing (memo sheet)



Directly determine the value

_ 1 string

If the text itself contains quotation marks (double quotation marks or single quotation marks) or backslash used for character reference, you should add a backslash before them, which is the escape. Escape allows you to directly enter any characters in the text, including backslash.

The following table lists all escape characters supported by FreeMarker.



Native string: in native strings, The backslash and $ {do not have any special meaning. They are considered normal characters. To indicate that the string is a native string, place the letter r before the start quotation marks or single quotation marks, for example:

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

_ 2 You can directly specify a number without quotation marks when entering a number. points must be used as decimal separators instead
Other group separators.

_ 3 if the Boolean value is set to true or false, a Boolean value is expressed without quotation marks.


_ 4 Sequence
Specify the sequence of a text, use commas to separate each sub-variable, and place the entire list in square brackets. For example:

<#list ["winter", "spring", "summer", "autumn"] as x> ${x} </#list>
If the project in the list is an expression, you can also do this: [2 + 2, [1, 2, 3, 4], "whatnot"], where the first sub-variable is number 4, the second sub-variable is a sequence, and the third sub-variable is the string "whatnot ". You can also use start... end to define the sequence for storing the number range. Here, start and end are the number of processed items.
Value expressions, such as 2 .. 5 and [2, 3, 4, 5], are the same, but the former is more efficient (with less memory usage and faster speed ). We can see that the former does not use square brackets. This can also be used to define the decreasing Numerical range, for example, 5 .. 2. (In addition, you can also omit the end, only 5 .., but this sequence contains 5, 6, 7, 8 by default.
)

_ 5 hash table
By specifying a hash table in the template, You can traverse the "Key/value" pairs separated by commas and put the list in curly brackets. Keys and values appear in pairs and are separated by colons. Let's take a look at this example: {"name": "green mouse", "price": 150 }. Note that the names and values are expressions, but the names used for retrieval must be string-type.

4. Search for variables
_ 1 top-level variable

To access the top-level variables, you can simply use the variable name.


_ 2 retrieve data from the hash table

If the result of an expression is a hash table, we can use the vertex and sub-variable name to get its value.

The following examples all have the same meanings: book. author. name, book ["author"]. name, book. author. ["name"], book ["author"] ["name"]

If we want to define the sub-variables of the same expression, there is another syntax format: The expression of any length string can be given in square brackets. In the above data model example, you can also obtain the title: book [test]: here the test is the value in the root element test.

_ 3 retrieve data from the sequence

This is the same as retrieving from a hash table, but you can only use square brackets syntax, And the expressions in square brackets must eventually be a number rather than a string. In the data model example in chapter 1, to obtain the name of the first animal (remember that the first index is 0 rather than 1), you can write animals [0]. name.


_ 4 special Variables

Special variables are defined by the FreeMarker engine itself. to use them, you can follow the syntax below
Run:. variable_name.
Generally, special variables are not needed, but may be used by professional users. Description of all special Variables
See the reference manual.


5 string operations

_ 1 interpolation (or join)

You can use $ {…} In string text {...} (#{...}). $ {...} Has the same role as in the region.

You can also use the + number to achieve similar results. This is an old method, also called string connection.


_ 2 get a character

User [0]

Obtain characters in a certain range, such as $ {user [1 .. 4]} and $ {user [4 ..]}. However, this method has been replaced and can be used as an alternative.
Function substring,

6. sequential operation
_ 1 Connection

Sequence connections can be performed using the + number, for example:

<#list ["Joe", "Fred"] + ["Julia", "Kate"] as user> - ${user} </#list> 
- Joe - Fred - Julia - Kate 

_ 2 sequence segmentation

Use [firstindex... lastindex] to obtain a part of the column in the order. Here, the result of the firstindex and lastindex expressions is a number. If the seq storage sequence "a", "B", "c", "d", "e", "f", then the expression seq [1 .. 4] It will be a sequence containing "B", "c", "d", "e" (the index of 1 is "B ", the index is "e "). Lastindex can be omitted, so it will be read to the end of the sequence. If the seq storage sequence "a", "B", "c", "d", "e", "f", seq [3 ..] it will be a sequence containing "d", "e", "f.

7. Hash Table operations
_ 1 Connection

Like connecting strings, you can also use the + sign method to connect to the hash table. If the two hash tables contain the same key, the items in the hash table on the right of the plus sign take precedence.

<#assign ages = {"Joe":23, "Fred":25} + {"Joe":30, "Julia":18}> - Joe is ${ages.Joe} - Fred is ${ages.Fred} - Julia is ${ages.Julia} 
Joe is 30 - Fred is 25 - Julia is 18

8 arithmetic operations
Sometimes we only want to obtain the integer part of the calculation result, which can be solved by using the built-in function int.
${(x/2)?int} ${1.1?int} ${1.999?int} ${-1.1?int} ${-1.999?int} 

9 Comparison
Use = (or use = in Java and C, the two values are exactly the same .) Test different values! =.

FreeMarker> can use it as the end character of the FTL tag. To avoid this problem, you have to put the expression in brackets: <# if (x> y)>, or you can use the <# if (x> y)> and <: <# if x> y>. You can use lt instead of <, lte instead of <=, gt instead>, and gte instead of> =. due to historical reasons, FTL also supports \ lt, \ lte, \ gt and \ gte, which have the same effect as using them without a backslash.

10 logical operations

11 built-in functions
Built-in functions? Form provides different forms or other information about variables. The syntax for using built-in functions is similar to the syntax for accessing hash table sub-variables, except for using? Number to replace
Point. For example, obtain the string in uppercase format: user? Upper_case.

Example:
${test?html} ${test?upper_case?html} 
Assume that the string test stores "Tom & Jerry", and the output is:
Tom & Jerry TOM & JERRY 

12. method call
${repeat("What", 3)} 
The output is as follows:
WhatWhatWhat 

13. Process nonexistent values

_ 1 default value
Usage Overview: unsafe_expr! Default_expr or unsafe_expr! Or (unsafe_expr )! Default_expr or (unsafe_expr )!
This operator allows you to specify a default value for a variable that might not exist.

For example, suppose there is no variable named mouse in the code shown below:

${mouse!"No mouse."} <#assign mouse="Jerry"> ${mouse!"No mouse."}
Will output
No mouse. Jerry 
The default value can be an expression of any type or a string. You can also write: hits! 0 or colors! ["Red", "green", "blue"]. The complexity of the default expression is not strictly limited. You can also write it like this: cargo. weight! (Item. weight * itemCount + 10 ).

_ 2 check for nonexistent values
Usage Overview: unsafe_expr ?? Or (unsafe_expr )?? This operator tells us whether a value exists. In this case, the result is true or false.
For example, assume there is no variable named "mouse:
<#if mouse??>  Mouse found <#else>  No mouse found </#if> Creating mouse... <#assign mouse = "Jerry"> <#if mouse??>  Mouse found <#else>  No mouse found </#if> 
No mouse found Creating mouse...  Mouse found

14 brackets
Parentheses can be used to group expressions. Example:
<# -- Output: -- >3 {3*2 + 2} <# -- 8 -- >$ {3*(2 + 2 )} <# -- 12 -- >$ {3*(2 + 2) * (1/2)} <# -- 6 -- >$ {"green" + "mouse "? Upper_case }< # -- green MOUSE -- >$ {("green" + "mouse ")? Upper_case }< # -- green mouse --> <# if! (Color = "red" | color = "green")> The color is nor red nor green </# if>

15. spaces in the expression
FTL ignores unnecessary spaces in the expression

16 operator priority

Interpolation
The syntax for interpolation is $ {expression}. expression can be all types of expressions (for example, ${100 + x }).
Interpolation is used to insert a specific value and convert it to text (string ). Interpolation can only be used in two locations:
Region (for example,

If the interpolation is in the escape area (that is, it is no longer in the string expression), if the escapse command takes effect, the string to be inserted will be automatically escaped.

<#escape x as x?html>  ...  <p>Title: ${book.title}</p>  <p>Description: <#noescape>${book.description}</#noescape></p>  








Does the freemarker template directly change the html file suffix to ftl?

Certainly.
It is only related to the freemarker configured on the web server and has nothing to do with the browser.
In addition, the webmaster group has products to buy, Which is cheap and guaranteed.

How can I block and redirect an error when the freemarker template is incorrect?

In the daily development process, reasonable handling of error information is an important part. Especially for portal systems, its importance is self-evident. However, in the actual development process, if the error prompt is clear and the customer does not feel so disgusted, most systems that seem to be in conflict use a uniform error page that is detected and then processed in a unified manner, however, the error detection is only an error that deals with big parts, such as java. SQL. SQLException, java. lang. runtimeException, but for systems that use the freemarker template language, its support is not very good (I tried to set freemarker. template. templateException and other exceptions are added to the detection mechanism. If the detection mechanism does not work, you have to use the implementation method instead ). By querying freemarker and spring APIs, freemarker provides an interface TemplateExceptionHandler that supports its error handling mechanism. You need to expand the implementation by yourself, constructing your own mechanism for handling freemarker template errors is mainly divided into two parts: 1. Constructing your own error handling mechanism 2. Adding custom error mechanisms to freemarker configuration at spring startup the procedure is as follows: 1. Create a new class to implement the TemplateExceptionHandler interface public class LenovoFreemarkerExceptionHandler implementsTemplateExceptionHandler {public void handleTemplateException (TemplateException arg0, Environment arg1, Writer out) throws TemplateException {// here, you can build your error mechanism to redirect and print error logs }}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.