I. Introduction of Freemaker
Freemarker is a free Java template engine, a tool for generating text based on templates and data (HMLT, e-mail, profiles, source code, etc.), which is not intended for end users, but a component used by programmers.
Freemarker was originally designed to generate HTML pages in the MVC pattern of web development, so it could run in a non-web application environment without binding the servlet or any web-related stuff.
History
The first edition of Freemarker was released in 1999, and at the beginning of 2002 the JAVACC (Java Compiler Compiler, a syntax analysis generator developed with Java) rewrote the core code of Freemarker. 2015 Freemarker code migrated to Apache.
GitHub Address: Github.com/apache/freemarker
Working principle
The freemarker template is stored on the server, and when a user accesses it, Freemarker queries the corresponding data, replaces the label in the template, and generates the final HTML returned to the user, such as:
Second, Freemarker basic use
The basic use is divided into 3 parts, 3 of which comprise the Freemarker:
- Instructions
- An expression
The directive is a special tag that Freemarker uses to identify the conversion, the expression is the specific syntax implementation in the tag, and the other parts are templates that are not well categorized.
2.1 Instructions
Use the FTL (freemarker template language) tag to invoke the instruction.
Quick Overview of commands:
- Assign
- Attempt, recover
- Compress
- Escape, Noescape
- Flush
- Ftl
- function, return
- Global
- If, else, ElseIf
- Import
- Include
- List, else, items, Sep, break
- Local
- Macro, nested, return
- Noparse
- Nt
- Setting
- Stop
- switch, case, default, break
- T, LT, RT
- Visit, Recurse, fallback
- User-defined labels
Down we see separately each instruction corresponds to the specific use.
2.1.1 Assign Code Declaration
Assign is divided into variables and code fragment declarations.
2.1.1.1 Variable Declaration
Can be a single-variable declaration, or a multivariable declaration, here is an example of a multivariable declaration:
<#assign name="adam" age=18 "sex"="man">${name} - ${age} - ${"sex"}
For a single variable, write only one.
2.1.1.2 Code Snippet Declaration
<#assign code> <#list ["java","golang"] as c> ${c} </#list></#assign>${code}
${code}
This is used to execute the method, and the code fragment will not execute if the session is not called.
2.1.2 attempt, recover exception instruction
Attempt (try), the Recover (recovery) instruction is similar to the program's try catch, as shown in the following example:
<#attempt> i am ${name} <#recover> error name</#attempt>
If the variable "name" is displayed normally, "I am XXX" is displayed and "Error name" is displayed if there is no variable.
2.1.3 Compress compressed code remove blank Lines
<#compress> 1 2 3 4 5 test only I said, test only</#compress>1 2 3 4 5test onlyI said, test only
The effect is as follows:
It is useful to remove blank lines in a format that is not sensitive to whitespace.
2.1.4 Escape, Noescape escaped, not escaped 2.1.4.1 escape use
<#escape x as x?html> ${firstName} ${lastName}</#escape>
The above code, similar to the following:
${firstName?html}${lastName?html}
Java code:
@RequestMapping("/")public ModelAndView index() { ModelAndView modelAndView = new ModelAndView("/index"); modelAndView.addObject("firstName", "<span style='color:red'>firstName</span>"); modelAndView.addObject("lastName", "lastName"); return modelAndView;}
The end result is:
2.1.4.2 "? HTML" syntax parsing
The single question mark is followed by an action function, similar to the method name in Java, where HTML is one of the built-in functions, indicating that the string is output according to HTML markup, with the following character substitution rules:
<
Replaced by<
>
Replaced by>
&
Replaced by&
"
Replaced by"
2.1.4.3 Noescape Use
HTML code:
<#escape x as x?html> <#noescape> ${firstName} </#noescape> ${lastName}</#escape>
Java code:
@RequestMapping("/")public ModelAndView index() { ModelAndView modelAndView = new ModelAndView("/index"); modelAndView.addObject("firstName", "<span style='color:red'>firstName</span>"); modelAndView.addObject("lastName", "lastName"); return modelAndView;}
Final effect:
2.1.5 function, return method declaration
Code format:
<#function name param1 param2 ... paramN> ... <#return returnValue> ...</#function>
- Name is the method name
- Param1, the Param2,paramn method passes over the arguments, can have an infinite number of arguments, or no arguments
- The return method returns a value that can appear anywhere in the function and occurs any number of times
The sample code is as follows:
<#function sum x y z> <#return x+y+z></#function>${sum(5,5,5)}
Note: function without return is meaningless, equivalent to returning NULL, and the information in the function is not printed to the page, the example is as follows:
<#function wantToPrint> 这里的信息是显示不了的</#function><#if wantToPrint()??> Message:${wantToPrint()}</#if>
“??” Used to determine if a value is NULL, if NULL is not performed. If you do not null directly using ${} to print, the template error will be reported, the effect is as follows:
2.1.6 Global Code Declaration
The syntax is as follows:
<#global name=value>或<#global name1=value1 name2=value2 ... nameN=valueN>或<#global name> capture this</#global>
Global usage is similar to assign usage, except that the global declaration is globally, and all namespaces are visible.
2.1.7 If elseif else condition judgment
The syntax is as follows:
<#if condition> ...<#elseif condition2> ...<#elseif condition3> ......<#else> ...</#if>
Examples are as follows:
<#assign x=1 ><#if x==1> x is 1<#elseif x==2> x is 2<#else> x is not 1</#if>
2.1.8 Import Introduction Template
Grammar:<#import path as hash>
Examples such as the following
The FOOTER.FTL code is as follows:
The INDEX.FTL code is as follows:
Final output content:
2.1.9 Include embedded templates Grammar:<#include path>
Examples such as the following
The FOOTER.FTL code is as follows:
The INDEX.FTL code is as follows:
The final content is as follows:
this is footer.ftl
2.1.10 list, else, items, Sep, break cycle 2.1.10.1 normal cycle Output 1-3 of the number, if equal to 2 jumps out of the loop, the code is as follows:
<#list 1..3 as n> ${n} <#if n==2> <#break> </#if></#list>
Note: "1..3" is equal to [all].
Results:1 2
2.1.10.2 using the items output Examples are as follows:
<#list 1..3><ul><#items as n> <li>${n}</li></#items></ul></#list>
2.1.10.3 Sep Use Skip the last item
<#list 1..3 as n> ${n} <#sep>,</#sep></#list>
Final Result:1 , 2 , 3
2.1.10.4 Array Last item The code is as follows:
<#list 1..3 as n> ${n} <#if !n_has_next> 最后一项 </#if></#list>
Use "Variable _has_next" to determine if there is a next option to find the last item, the final result:1 2 3 最后一项
2.1.11 macro Macro: is a code fragment of a variable name, for example:
<#macro sayhi name> Hello, ${name}</#macro><@sayhi "Adam" />
Equivalent to declaring a macro named "Sayhi" with a parameter "name", using the Custom label "@" to invoke the macro.
Results of the output:Hello, Adam
2.1.12 switch, case, Defalut, break multi-condition judgment The sample code is as follows:
<#assign animal="dog" ><#switch animal> <#case "pig"> This is pig <#break> <#case "dog"> This is dog <#break> <#default> This is Aaimal</#switch>
2.1.13 Extended Knowledge instruction automatically ignores whitespace properties
Freemarker ignores whitespace tags in the FTL tag, so you can write directly:
<#list ["老王","老李","老张"] as p> ${p}</#list>
Even if this format is not a problem, Freemarker will parse normally.
2.2-expression 2.2.1 string concatenation Character Stitching Code:
<#assign name="ABCDEFG">${"Hello, ${name}"}
Results:Hello, ABCDEFG
2.2.2 Arithmetic operation 2.2.2.1 arithmetic character There are five kinds of arithmetic characters:
+
-
*
/
%
Redundancy (to find a model)
Example code:
${100 - 10 * 20}
Output:
-100
2.2.2.2 Numeric conversions ${1.999?int}
Output:
1
Note: Numeric conversions are not rounded and are discarded after the decimal point.
2.2.3 built-in functions (emphasis) Built-in functions: equivalent to the inside of our Java class internal methods, very common, commonly used built-in functions are: time-built functions, character built-in functions, the number of built-in functions and so on.
2.2.3.1 the use and difference of a single question mark and two question marks Single question mark: In Freemarker, call the built-in function with a single question mark, for example: Look at the ${"admin"?length}
character length of the string "admin", where length is the built-in function of the string.
Double quotation marks: Indicates whether the value is null, for example:
<#if admin??> Admin is not null</#if>
2.2.3.2 string built-in function 2.2.3.2.1 whether it contains a judgment Using contains, the code example:
<#if "admin"?contains("min")> min<#else >not min</#if>
Output:
min
2.2.3.2.2 Uppercase and lowercase conversions Example code:
<#assign name="Adam">${name?uncap_first} ${name?upper_case}${name?cap_first}${name?lower_case}
Output:
adam ADAM Adam adam
More string built-in functions: freemarker.apache.org/docs/ref_builtins_string.html
2.2.3.3 numeric built-in functions Example code:
${1.23569?string.percent}${1.23569?string["0.##"]}${1.23569?string["0.###"]}
Output:
124% 1.24 1.236
Attention:
- Use String.percent to calculate percentages, which are automatically rounded.
- Use "? string[" 0.## "]" to customize the number of decimal points, automatically rounded.
2.2.3.4 time-built function 2.2.3.4.1 timestamp conversion to any time format Code:
<#assign timestamp=1534414202000>${timestamp?number_to_datetime?string["yyyy/MM/dd HH:mm"]}
Output:
2.2.3.4.2 time Formatting Example code:
<#assign nowTime = .now>${nowTime} <br />${nowTime?string["yyyy/MM/dd HH:mm"]} <br />
Output:
More built-in methods: freemarker.apache.org/docs/ref_builtins.html
Third, Spring Boot Integration 3.1 Set environment
- Spring Boot 2.0.4
- Freemaker 2.3.28
- JDK 8
- Windows 10
- Idea 2018.2.1
3.2 Integrated Step 3.2.1 Pom.xml Add Freemaker Dependency <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId></dependency>
3.2.2 Application.properties Configuration Template The main configuration is as follows:
## Freemarker 配置spring.freemarker.template-loader-path=classpath:/templates/spring.freemarker.cache=falsespring.freemarker.charset=UTF-8spring.freemarker.check-template-location=truespring.freemarker.content-type=text/htmlspring.freemarker.expose-request-attributes=falsespring.freemarker.expose-session-attributes=falsespring.freemarker.request-context-attribute=requestspring.freemarker.suffix=.ftl
Configuration Items |
type |
Default Value |
Recommended Values |
Description |
Spring.freemarker.template-loader-path |
String |
classpath:/templates/ |
Default |
Template Storage Path |
Spring.freemarker.cache |
bool |
True |
Default |
Whether to turn on caching, generate environment recommendations open |
Spring.freemarker.charset |
String |
- |
UTF-8 |
Coding |
Spring.freemarker.content-type |
String |
Text/html |
Text/html |
Content-type type |
Spring.freemarker.suffix |
String |
. FTL |
. FTL |
Template suffix |
Spring.freemarker.expose-request-attributes |
bool |
False |
False |
Set all request properties to be added to the model when you merge to the template |
Spring.freemarker.expose-session-attributes |
bool |
False |
False |
Sets all httpsession properties to be added to the model when the merge is in the template. |
Spring.freemarker.request-context-attribute |
String |
- |
Request |
The name of the RequestContext property |
More configurations:
# Freemarker (freemarkerproperties) spring.freemarker.allow-request-override=false # Whether HttpServletRequest Attributes is allowed to override (hide) controller generated model attributes of the same name.spring.freemarker.allow-s Ession-override=false # Whether HttpSession attributes is allowed to override (hide) controller generated model attribute S of the same Name.spring.freemarker.cache=false # Whether to enable template Caching.spring.freemarker.charset=utf-8 # Te Mplate encoding.spring.freemarker.check-template-location=true # Whether to check, the templates location exists.spring.freemarker.content-type=text/html # content-type Value.spring.freemarker.enabled=true # Whether to Enable MVC view resolution for this Technology.spring.freemarker.expose-request-attributes=false # Whether all request at Tributes should is added to the model prior to merging with the Template.spring.freemarker.expose-session-attributes=false # Whether All HttpSession attributes should is added toThe model prior to merging with the Template.spring.freemarker.expose-spring-macro-helpers=true # Whether to expose a Requ Estcontext for use by Spring's macro library, under the name "Springmacrorequestcontext". Spring.freemarker.prefer-file-system-access=true # Whether to prefer the file system access for template loading. File system access enables hot detection of the template changes.spring.freemarker.prefix= # prefix that gets prepended to vie W names when building a url.spring.freemarker.request-context-attribute= # Name of the RequestContext attribute for all VI ews.spring.freemarker.settings.*= # well-known Freemarker keys which is passed to Freemarker ' s CONFIGURATION.SPRING.FREEMARKER.SUFFIX=.FTL # suffix that gets appended to view names when building a URL.spring.freemarke r.template-loader-path=classpath:/templates/# comma-separated List of template paths.spring.freemarker.view-names= # White list of view names so can be resolved.
3.2.3 Writing HTML code
3.2.4 Writing Java code New Index.java file, Application.java (entry file) code is inconvenient, Index.java code is as follows:
import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.servlet.ModelAndView;@Controller@RequestMapping("/")public class Index { @RequestMapping("/") public ModelAndView index() { ModelAndView modelAndView = new ModelAndView("/index"); modelAndView.addObject("name", "老王"); return modelAndView; }}
Key code Interpretation:
- @Controller Note: To identify yourself as a controller, you only need to configure @requestmapping, you can map the user URL to the controller;
- Use the Modelandview object to specify the view name & Add View object.
3.2.5 Run After performing the above 4 steps, you can run the Java project, if idea uses the default shortcut "Shift + F10" To start debugging, page access: http://localhost:8080/can see the following effect:
Iv. references Freemarker Official Document: freemarker.apache.org/
Freemarker translation of the Chinese website:/http