Common syntax
Eg. An object book
1. Output $ {book. name}
Null Value Judgment: $ {book. Name? If_exists },
$ {Book. Name? Default ('xxx')} // default value: XXX
$ {Book. Name! "XXX"} // default value: XXX
Date Format: $ {book. Date? String ('yyyy-mm-dd ')}
Digit format: $ {book? String. Number} -- 20
$ {Book? String. Currency} -- <# -- $20.00 -->
$ {Book? String. percent}-<# -- 20% -->
Insert a Boolean value:
<# Assign Foo = ture/>
$ {Foo? String ("yes", "no") }< # -- yes -->
2. logical judgment
A:
<# If condition>...
<# Elseif condition2>...
<# Elseif condition3> ......
<# Else>...
The null value can be judged as <# If book. Name ?? >
</# If>
B:
<# Switch value>
<# Case refvalue1>
...
<# Break>
<# Case refvalue2>
...
<# Break>
...
<# Case refvaluen>
...
<# Break>
<# Default>
...
</# Switch>
3. Loop reading
<# List sequence as item>
...
</# List>
Null Value Judgment <# If booklist? Size = 0> </# list>
E.g.
<# List employees as E>
$ {E_index}. $ {e. name}
</# List>
Output:
1. readonly
2. Robbin
4. freemarker
3. Macro/template
Macro macro
Macros are defined using macro commands in the template.
L.1 basic usage
A macro is a template snippet associated with a variable to use the variable in the template using user-defined instructions. The following is an example:
<# Macro greet>
<Font size = "+ 2"> Hello Joe! </Font>
</# Macro>
When calling a macro, it is similar to other commands that use freemarker,
Only use @ to replace # In the FTL tag #.
<@ Greet> </@ greet>
<# -- <@ Greet/> -->
In macro commands, you can define parameters after macro variables, for example:
<# Macro greet person>
<Font size = "+ 2"> Hello $ {person }! </Font>
</# Macro>
You can use this macro variable as follows:
<@ Greet person = "Fred"/>
But the followingCodeDifferent meanings:
<@ Greet person = Fred/>
This means to pass the value of the Fred variable to the person parameter. The value is not only a string, but also other types, or even complex expressions.
Macros can have multiple parameters. The following is an example:
<# Macro greet person color>
<Font size = "+ 2" color = "$ {color}"> Hello $ {person }! </Font>
</# Macro>
You can use this macro variable in this way, where the order of parameters is irrelevant:
<@ Greet person = "Fred" color = "black"/>
You can specify the default value when defining parameters. Otherwise, you must assign values to all parameters when calling macros:
<# Macro greet person color = "black">
<Font size = "+ 2" color = "$ {color}"> Hello $ {person }! </Font>
</# Macro>
Note: macro parameters are local variables and can only be valid in macro definitions.
Nested content in a macro
Freemarker macros can have nested content,
<# Nested> the command executes the template snippet between the start and end mark of the macro call command. For example:
<# Macro Border>
<Table border = 4 cellspacing = 0 cellpadding = 4> <tr> <TD>
<# Nested>
</Tr> </TD> </table>
</# Macro>
Execute macro call:
<@ Border> the bordered text </@ Border>
Output result:
<Table border = 4 cellspacing = 0 cellpadding = 4>
<Tr> <TD>
The bordered text
</Tr> </TD>
</Table>
<# Nested> the command can be called multiple times and the same content is executed each time.
<# Macro do_thrice>
<# Nested>
<# Nested>
<# Nested>
</# Macro>
<@ Do_thrice>
Anything.
</@ Do_thrice>
Fmpp output result:
Anything.
Anything.
Anything.
The nested content can be valid FTL. The following is a complex example. We combine the above three macros:
<@ Border>
<Ul>
<@ Do_thrice>
<Li> <@ greet person = "Joe"/>
</@ Do_thrice>
</Ul>
</@ Border>
Output result:
<Table border = 4 cellspacing = 0 cellpadding = 4> <tr> <TD>
<Ul>
<Li> <font size = "+ 2"> Hello Joe! </Font>
<Li> <font size = "+ 2"> Hello Joe! </Font>
<Li> <font size = "+ 2"> Hello Joe! </Font>
</Ul>
</Tr> </TD> </table>
The local variables in the macro definition are invisible to the nested content, for example:
<# Macro repeat count>
<# Local Y = "test">
<# List 1.. count as x>
$ {Y }$ {count}/$ {x }:< # nested>
</# List>
</# Macro>
<@ Repeat count = 3 >$ {Y? Default ("? ") }$ {X? Default ("? ")} $ {Count? Default ("? ")} </@ Repeat>
Output result:
Test 3/1 :? ? ?
Test 3/2 :? ? ?
Test 3/3 :? ? ?
Use cyclic variables in macro definition
The nestted command can also contain cyclic variables (for the meanings of cyclic variables, see the next section). When macro is called, the names of cyclic variables are listed after the parameters of the macro command in the following format:
<@ Macro_name paramter list; Loop Variable list [,]>
For example:
<# Macro repeat count>
<# List 1.. count as x>
<# Nested X, X/2, x = count>
</# List>
</# Macro>
<@ Repeat count = 4; C, halfc, last>
$ {C}. $ {halfc} <# If last> last! </# If>
</@ Repeat>
Here, count is the macro parameter. C, halfc, and last are the cyclic variables. The output result is as follows:
0.5.
2. 1
3. 1.5
4. 2 last!
The difference between the specified loop variable and macro tag does not occur. If the loop variable is not specified during the call, the extra values are invisible. When the call is made, multiple cyclic variables and redundant cyclic variables are specified.
Not created:
<@ Repeat count = 4; C, halfc, last>
$ {C}. $ {halfc} <# If last> last! </# If>
</@ Repeat>
<@ Repeat count = 4; C, halfc>
$ {C}. $ {halfc}
</@ Repeat>
<@ Repeat count = 4>
Just repeat it...
</@ Repeat>
Define variables in the template
There are three types of variables defined in the template:
Plain variable: it can be accessed anywhere in the template, including the template inserted using the include command, which is created and replaced using the assign command.
Local variables: valid in the macro definition. Use the local command to create and replace the variables.
Loop Variable: it can only exist in the nested content of the command and is automatically created by the Command (such as list). The macro parameter is a local variable, not a loop variable.
Partial Variables hide (rather than overwrite) plain variables with the same name. Cyclic variables hide local variables with the same name and plain variables. The following is an example:
<# Assign x = "plain">
$ {X} <# -- we see the plain var. Here -->
<@ Test/>
6. $ {x} <# -- the value of plain var. was not changed -->
<# List ["loop"] As x>
7. $ {x} <# -- now the loop var. Hides the plain var. -->
<# Assign x = "plain2"> <# -- replace the plain var, hiding does not mater here -->
8. $ {x} <# -- it still hides the plain var. -->
</# List>
9. $ {x} <# -- the new value of plain var. -->
<# Macro test>
2. $ {x} <# -- we still see the plain var. Here -->
<# Local X = "local">
3. $ {x} <# -- now the local var. Hides it -->
<# List ["loop"] As x>
4. $ {x} <# -- now the loop var. Hides the local var. -->
</# List>
5. $ {x} <# -- now we see the local var. Again -->
</# Macro>
Output result:
1. Plain
2. Plain
3. Local
4. Loop
5. Local
6. Plain
7. Loop
8. Loop
9. plain2
Internal Loop variables hide External Loop variables with the same name, such:
<# List ["loop 1"] As x>
$ {X}
<# List ["loop 2"] As x>
$ {X}
<# List ["loop 3"] As x>
$ {X}
</# List>
$ {X}
</# List>
$ {X}
</# List>
Output result:
Loop 1
Loop 2
Loop 3
Loop 2
Loop 1
The variables in the template hide (rather than overwrite) the variables with the same name in the data model. To access the variables with the same name in the data model, use the special variable global. The following example assumes that the data
The user value in the model is Big Joe:
<# Assign user = "Joe hider">
$ {User} <# -- prints: Joe hider -->
$ {. Globals. User} <# -- prints: Big Joe -->
Namespace
Generally, only one namespace is used, which is called the primary namespace. However, to create reusable macro, converter, or other variable sets (usually called libraries), multiple namespace must be used,
The purpose is to prevent conflicts of the same name
Create a database
The following is an example of creating a database (Suppose it is saved in lib/my_test.ftl ):
<# macro copyright date>
copyright (c) $ {date} Julia Smith. all rights reserved.
Email: $ {mail}
<# assign mail = "jsmith@acme.com">
import data to the template using the import command, freemarker creates a new namespace for the imported database and can access the variables in the database through the hash variables specified in the import command:
<# import "/lib/my_test.ftl" as my>
<# assign mail = "fred@acme.com">
<@ My. copyright date = "19 99-2002 "/>
$ {My. mail}
$ {mail}
output:
copyright (c) 1999-2002 Julia Smith. all rights reserved.
Email: jsmith@acme.com
jsmith@acme.com
the two variables with the same name in the example do not conflict, because they are in different namespaces. You can also use the assign command to create or replace variables in the imported namespace.
The following is an example:
<# Import "/lib/my_test.ftl" as my>
$ {My. Mail}
<# Assign mail = "jsmith@other.com" in my>
$ {My. Mail}
Output result:
Jsmith@acme.com
Jsmith@other.com
Variables in the data model are visible anywhere and contain different namespaces. The following is the modified Library:
<# Macro copyright date>
<P> copyright (c) $ {date }$ {user}. All Rights Reserved. </P>
</# Macro>
<# Assign mail = "$ {user} @ acme.com">
Assume that the value of the user variable in the data model is Fred, the following code:
<# Import "/lib/my_test.ftl" as my>
<@ My. copyright date = "1999-2002"/>
$ {My. Mail}
Output result:
<P> copyright (c) 1999-2002 Fred. All Rights Reserved. </P> Fred@acme.com
4. Combination of freemarker and struts
1. Replace the output file with a file in FTL format.
E.g.
<Action name = "bookactionform" parameter = "method" Path = "/bookaction" Scope = "request" type = "example. bookaction"
Validate = "true">
<Forward name = "list" Path = "/index. FTL"/>
</Action>
2. Use struts, jstl, and other labels
A. Import à <# global html = jsptaglibs ["/WEB-INF/tags/struts-html.tld"]>
Or <# assign html = jsptaglibs ["/WEB-INF/struts-html.tld"]>
<# Assign bean = jsptaglibs ["/WEB-INF/struts-bean.tld"]>
<# Assign logic = jsptaglibs ["/WEB-INF/struts-logic.tld"]>
B. Use <@ bean. Page id = "request" property = "request"/>,
<@ Html. Text property = "VO. newstitle" styleclass = "input1"/>
5. Use freemarker to generate HTML pages
Example: makefilemanager. Java
Package example;
Import freemarker. template. configuration;
Import java. Text. simpledateformat;
Import java. Io. file;
Import freemarker. template. defaultobjectwrapper;
Import java. util. Map;
Import java. util. hashmap;
Import java. Io. Writer;
Import java. Io. outputstreamwriter;
Import java. Io. fileoutputstream;
Import freemarker. template. templateexception;
Import java. Io. ioexception;
Import freemarker. template. template;
Public class makefilemanager {
Public String make (book, bookftl ){
Configuration CFG = new configuration (); // Configuration
String realpath = bookftl. getrealpath ();
String templatepath = realpath + "/WEB-INF/templates/book ";
String cdatestr = "book/" +
New simpledateformat ("yyyymmdd"). Format (New java. util.
Date ());
String filepostfix = ". html ";
String Path = realpath + "/" + cdatestr;
String filetimename = new simpledateformat ("yyyymmddhhmmss"). Format (New
Java. util. Date ());
String returnfilename = cdatestr + "/" + filetimename + filepostfix;
String filename = "";
File bookdir = new file (PATH );
If (bookdir. exists ()){
Filename = path + "/" + filetimename + filepostfix;
} Else {
Bookdir. mkdirs ();
Filename = path + "/" + filetimename + filepostfix;
}
Try {
// Set freemarker Parameters
Cfg. setnumberformat ("0. #########"); // the Web. xml configuration is invalid when an HTML file is generated.
// Cfg. setencoding ();
Cfg. setdirectoryfortemplateloading (new file (templatepath ));
Cfg. setobjectwrapper (New defaultobjectwrapper ());
Template booktemplate = cfg. gettemplate (bookftl. gettemplatename (); // template object
Map root = new hashmap ();
Root. Put ("book", book );
Root. Put ("book2", book );
Writer out = new outputstreamwriter (New fileoutputstream (filename ));
Try {
Booktemplate. Process (root, out );
} Catch (templateexception e ){
E. printstacktrace ();
}
Out. Flush ();
} Catch (ioexception e ){
E. printstacktrace ();
}
Return returnfilename;
}
}