Freemarker usage Summary

Source: Internet
Author: User

1. Use of freemarker template engine: Template + Data Model = Output
1) freemarker template: a common text file that uses some special tags of freemarker.
2) Data Model: It stores the data structure of the data, usually a Hash Storage Structure (for example, hashmap)
3) freemarker framework combines data in a data model into a template to generate output.

2. Configure the use environment: Download (http://www.freemarker.org/) and add the freemarker-2.x.x.jar to the classpath of the application.

 

3. Java applications:
1) create a data model: Map <string, Object> root = new hashmap <string, Object> ();
2) create a template file: templates/first. FTL
3) Merge:
// Create a configuration instance for initial freemarker configuration // Add a configuration named freemarker. properties under classpath
Configuration CFG = new configuration ();
// Set the directory for storing template files
Cfg. setdirectoryfortemplateloading (new file ("templates "));
// Load the specified Template
Template T = cfg. gettemplate ("first. FTL ");
// Process Merging
T. Process (root, new outputstreamwriter (system. Out ));

 

4. Use freemarker directly in Web applications: In the Servlet request processing method:
// Create a configuration instance for initial freemarker Configuration
Configuration CFG = new configuration ();
// Set the directory for storing template files
Cfg. setservletcontextfortemplateloading (getservletcontext (), "/templates ");
// Load the specified Template
Template T = cfg. gettemplate ("first. FTL", "UTF-8 ");
// Process Merging
T. Process (root, response. getwriter ());

 

★5. FTL (freemarker template language) Syntax:

1) The template file consists of four parts:
A) Text: directly output part
B) Note: <# -- Comment content --> NO output
C) interpolation: $ {expression} Or # {expression}. The data in the data model is replaced before being output.
D) FTL command:
Built-in (pre-defined) commands: <# command name attribute name = "value"> subject </# command name> example: <# If user ???> $ {User. loginname} </# If>
Custom command: <@ command name attribute name = "value"> subject </@ command name>

 

2) interpolation rules
A) The expression is placed in the interpolation syntax $ {} to output the value of the expression.
B) The expression value type can be string, number, Boolean, date and time, sequence, or hash structure.
C) expressions support all operators in Java:
Arithmetic Operators: +,-, *,/, and %
Comparison operators: = (EQ ),! = (NE),> (GT),> = (GTE), <(LT), <= (LTE)
Logical operators: & (and), | (OR ),! (Not)
Three-object OPERATOR :? :

D) built-in functions:
I) usage: expression? Function name [(real parameter)]
Ii) Common built-in functions of strings: substring (from [, to]), HTML, length, trim, URL
Example: <# setting url_escaping_charset = "UTF-8">, exp? URL [("UTF-8")]
Iii) Common built-in functions of numbers: C, string [(digit mode string)],
Iv) Boolean built-in function: String [("male", "female")]
V) built-in common date and time functions: String [("Format mode string")], datetime, date, and time
E) sequence:
Sequence defined in FTL: included in square brackets. Each element is separated by a comma, for example, <# assign seq = ["Winter", "Spring", "Summer ", "Autumn"]>
You can also use the number range (ascending or descending) to define the sequence: <# assign Nums = 101... 105> or <# assign Nums = 105 .. 101>
In the data model: it can be a list object or a set object.
Common built-in functions of sequence: Size and sort [("specify fields for sorting")]
F) Hash structure:
When defined directly in the FTL file: it is included in braces and separated by commas (,). Keys and values are separated by colons. The key must be a string.

For example: <# assign scores = {"language": 78, "Mathematics": 89, "English": 87 }>$ {scores. Language}
In the data model: it can be a map object.
Built-in functions of the hash structure: Size, keys, values

 

3) Determination of null values in freemarker
A) judge whether it is null: use ?? (? If_exists ,? Exists) if not null, true is returned; otherwise, false is returned.
B) Configure configuration: configuration CFG = new configuration (); cfg. setclassiccompatible (true );
C) attribute configuration method: In the freemarker. properties file, classic_compatible = true
D) set through FTL: Add <# setting classic_compatible = true> before the FTL file header.
E) when traversing the sequence and hash structure in FTL: <# If userlist ???> <# List userlist as user>... </# list> </# If>

4) Common built-in commands:
A) if/else
<# If condition>
...
<# Elseif condition2>
...
<# Elseif condition3>
...
...
<# Else>
...
</# If>

B) switch/case
<# Switch value>
<# Case refvalue1>
...
<# Break>
<# Case refvalue2>
...
<# Break>
...
<# Case refvaluen>
...
<# Break>
<# Default>
...
</# Switch>

C) List
<# List sequence as item> <# -- item_index index of the current iteration -->
...
</# List>

D) Include contains the specified file. Similar to the include standard action in JSP
<# Include "file path" [encoding = "charset"] [parse = true | false]>

E) import all variables in the specified template.
<# Import "file path" as hash>
 
F) noparse does not process the content contained in this command
<# Noparse>
...
</# Noparse>

G) Assign: Creates or replaces a top-level variable for the current template page.
<# Assign name = value>
<# Assign name1 = value1 name2 = value2... Namen = valuen>

H) Global: Creates or replaces the top-level variable of the global scope of a namespace.
I) Local: Create or replace a local top-level variable
J) Setting sets the attributes of freemarker during runtime. Syntax: <# setting name = value>
Commonly used names include:
Locale: Language Environment option used by the template. En, ZH, zh_cn, zh_tw
Number_format: Format of the number formatted output
Boolean_format: Format of the output formatted with a Boolean Value
Date_format, time_format, datetime_format: Format of the date and time formatted output
Time_zone: format the time zone used by the output date and time.
Url_escaping_charset: URL-encoded character set.

K) custom commands: <# macro command Name property name ...... </# macro>
A paging tag written with custom commands see my blog: http://blog.csdn.net/qjyong/archive/2009/10/18/4693142.aspx

 

6. Integration of freemarker in Web applications: freemarker provides the freemarkerservlet class to integrate templates into Web applications:
1) The servlet has three hash structures in the data model:
Request, session, and application are used to access the attributes in the request, session, and application context respectively.
When the attribute in the access scope is not specified, the hash structure name is searched in the order of request, session, and application.
2) It also provides a hash structure named requestparameters to access the parameter data in the HTTP request.

7. freemarker integration in struts2: struts2 uses freemarker by default to generate HTML tags for all UI tags.
1) freemarkerresult is provided to support FTL pages.
<Result type = "freemarker">/templates/info. FTL </result>
2) freemarker provides the following built-in hash structure for struts2:
A) STACK: represents valuestack itself

B) Action: indicates the action instance that has just been executed.
C) Response: represents the hpptservletresponse instance
D) RES: indicates the hpptservletresponse instance.
E) Request: represents the hpptservletrequest instance
F) Req: represents the hpptservletrequest instance.
G) Session: indicates the hpptsession instance.
H) Application: represents the servletcontext instance
I) Base: indicates the context path of the user request.

 

8. Use freemarker to perform static page conversion:

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.