Freemarker Common Skills (iii)

Source: Internet
Author: User

Freemarker Template Parsing process

For example: a Freemarker expression <body> ${hello} </body>, which will be parsed into three parts, respectively
<body>
${hello}
</body>
The body tag in front and back is defined as TextBlock in Freemarker, and the middle variable is defined as dollarvariable. So the current structure is rootexpression = TextBlock dollarvariable TextBlock. Once the interpreter comes in, the rootexpression will be parsed, and rootexpression will call TextBlock dollarvariable TextBlock in turn to parse. Different types will do different operations, according to the context parameters passed in the corresponding assignment and output and so on.
When the template initiates an interpretation, the environment enters the access action that invokes the root element, and the root element accesses the contained templateelement in turn until all the leaf nodes are accessed. These access actions are controlled by calling environment's visit method, environment do the necessary operations, and then invoke the access operation of the corresponding node based on the type of node accessed. When accessing an element node that contains an interpreter, the interpreter is started to do the interpreting operation, according to the expression type, call GetStringValue, and pass in the parameter environment, An expression of the corresponding type is interpreted according to environment to get the value of the input string, which is returned and written to the response stream, which is interpreted as complete.

Introduction to the Freemarker function in the building

sequence built-in functions
1.sequence?first returns the first value of a sequence.
2.sequence?last returns the last value of the sequence.
3.sequence?reverse reverses the existing order of the sequence, which is the reverse sort
4.sequence?size returns the size of the sequence
5.sequence?sort to convert an object in sequence to a string after ordering
6.sequence?sort_by (value) is sorted by the property value of the object in sequence
Note: sequence cannot be null
built-in function of hash
1.hash?keys returns all keys in the hash and returns the result as sequence
2.hash?values returns all value in the hash and returns the result as sequence
manipulating string built-in functions
1.substring (start,end) intercepts substrings from a string
Start: Intercept the index at which the substring starts, start must be greater than or equal to 0, less than or equal to end
End: Truncate the length of the substring, end must be greater than or equal to 0, less than or equal to the length of the string, if omitted, the string length is the default.
2.cap_first the first word in a string to uppercase.
3.uncap_first the first word in a string into lowercase.
4.capitalize capitalize the first letter of all words in a string
5.date,time,datetime converting a string to a date
Note: An error is raised if the specified string is not properly formatted
6.ends_with determines whether a string is terminated by a substring, returns a Boolean value
Note: The Boolean value must be converted to a string to output
7.html is used to replace <, >, &, and "in the string with the corresponding <>&quot:&amp
8.index_of (Substring,start) finds a substring in the string, returns the index of the first character of the substring found, and returns 1 if no substring is found.
The start parameter is used to specify that the search starts at that index of the string and start is a numeric value.
If start is greater than the string length, the start value equals the string length, and if start is less than 0, start takes a value of 0.
9.length returns the length of a string
10.lower_case converting a string to lowercase
11.upper_case string to uppercase
12.contains determines whether a substring is contained in a character. Returns a Boolean value
Note: The Boolean value must be converted to a string to output
13.number converting a string to a number
14.replace is used to replace a portion of a string from left to right with a different string.
15.split splits a string into a set of strings using the specified delimiter
16.trim Delete string and trailing spaces
manipulating numeric built-in functions
1.C is used to convert a number to a string
2.string is used to convert a number to a string
Three number formats were booked in Freemarker: number,currency (currency) and percent (percent) where number is the default numeric format conversion
manipulating Boolean built-in functions
string is used to convert a Boolean value to a string output
True to "true", false to "false"
Foo?string ("Yes", "no") if the Boolean value is True, then return "yes", otherwise return no

Freemarker Log Implementation Process analysis

Freemarker has its own log class, which is an abstract class, specific log printing delegated to classpath inside the appropriate log jar to execute, looking for the appropriate log jar to find the order is: Apache log4j, Apache Avalon Logkit, JDK log. If a suitable log implementation class is not found, the log function will be suppressed and the error message will be printed using System.err.
If we want to specify the type of log we use, we can do so by:
loger.selectloggerlibrary (int library);
Note: Be sure to set in the Freemarker initialization phase before any Freemarker API is called, otherwise freemarker will bind to the default log implementation, so that the log modifications you specify will not work.

Use of greater than sign > in Freemarker

In Freemarker, when comparing the size of the data, pay attention to the use of the greater than sign (>). If you do not pay attention, the program will occur exception information, such as the following example:

1234 <#assign x = 4> <#if x>5 > x >5 </#if >

The above way to compare, will be abnormal, because of freemarker internal parsing processing reasons, x>5 in the greater than the number will be with < #if中的小于号进行配对, resulting in resolution problems. There are two ways to solve this situation:
Method One: Add parentheses.

1234 <#assign x = 4> <#if (x>5) > x > 5 </#if >

Method Two: Use the GT symbol.

1234 <#assign x = 4> <#if x GT 5 > x > 5 </#if >

To summarize:

There is a small problem when using >= and >. Freemarker interprets > as a terminator to the FTL tag. In order to avoid this problem, the expression must be placed in parentheses:< #if (x > Y), in addition, you can use LT instead of <,lte instead of <=,GT instead of >,gte instead of >=. For historical reasons, FTL also supports \LT,\LTE,\GT and \gte, using them just as they do without backslashes.

Summary of the key knowledge of the sequence (1) The default value for the sequence is [], see the following example:

< #if (winnerslist![])? Size GT 0>
<table class= "winner_table" border= "0" cellspacing= "0" cellpadding= "0" >
<tr>
<th class= "Bdr_gray" > Winning account </th>
<th> Guessing Difference </th>
</tr>
< #list winnerslist as list>
<tr>
&LT;TD class= "Bdr_gray" >${list.accountid! ""} </td>
<td>${list.deviation! ""} </td>
</tr>
</#list >
</table>
</#if >
Note: In the example above, winnerslist defaults to [], and its built-in function is size

(2) Sequence of connections:

You can concatenate two sequences into a new sequence, and the operator of the join sequence is ' + ', as shown in the following example:
< #list ["one", "two", "three"] + ["Four", "five", "six"] as x>
${X}
</#list >
The output results are as follows:
123456

(3) Segmentation of sequences:

For example, the segmentation scenario of a sequence: sometimes we do not need to display such a long string in the page, such as news headlines, so that the following example can be used to customize the length of the display
< #if title.content?length Lt 8>
<a Href>${title.content?default ("")}</a>
< #else >
<a href title= "${title.content}" >${title.content[0..3]?default ("")}</a>
</#if >
The function of the above example is: if the length of the string is less than 8, then the normal display, and vice versa to take 4 bits.
The following two points should be noted for the segmentation of sequences:
Lastindex can be omitted from the Freemarker 2.3.3 version.
If you attempt to access an item that precedes a sequence's first variable or an entry after an end variable, it will cause an error and the execution of the template will be interrupted.

(4) Definition of sub-sequence:

The item in the sequence is an expression, then you can do the following: [2 + 2, [1, 2, 3, 4], "What"], where the first sub-variable is the number 4, the second is a sequence, and the third is the string "what".

(5) The definition of a sequence of numbers:

The first way to define a sequence:
< #assign nums=[1,2,3,4,5,77,8,99]/>
Use the list command to output the sequence,
< #list Nums as num>
${num}
</#list >
The second way to define a sequence
Defines a sequential sequence,
< #assign nums=12..99/>
The contents of the sequence defined in this way are 12 to 99
Description
As can be seen from the example above, the sequence can also be used with start. End defines a sequence that stores a range of numbers, where start and end are processed numeric value expressions, such as 2. 5 and [2, 3, 4, 5] are the same, but using the former is more efficient (less memory and faster). It can be seen that the former also does not use square brackets, which can also be used to define a descending range of numbers, such as 5. 2. (In addition, you can omit end, just 5.) , but the sequence defaults to include 5,6,7,8 increments until infinity).

(6) Determining whether a sequence contains an element

If you want to determine whether a specified element is contained in a sequence, you can use the sequence's built-in function, Seq_contains.
Note: Seq_contains this built-in function is available from Freemarker version 2.3.1. It does not exist in version 2.3.
<#--declares a sequence that consists of several elements--
< #assign x = ["Red", +, "blue", "cyan"]>
<#--uses Seq_contains to determine whether elements in a sequence exist--
"Blue": ${x?seq_contains ("Blue")? String ("Yes", "No")}
"Yellow": ${x?seq_contains ("Yellow")? string ("Yes", "No")}
: ${x?seq_contains (+)? string ("Yes", "No")}
"+": ${x?seq_contains ("+")? String ("Yes", "No")}
Output Result:
"Blue": Yes
"Yellow": No
16:yes
"+": No
Attached: The seq_ prefix is required in this built-in function and is used to separate from the contains area. The contains function is used to look up substrings in a string (since the variable can be treated as both a string and a sequence).

The use of Stringtemplateloader

As a template framework, Freemarker's functionality is still very powerful. In the aspect of template processing, Freemarker has many forms, the most common way is to put the template file under a unified folder, the following form:
Configuration cfg = new configuration ();
Cfg.setdirectoryfortemplateloading (New File ("Templates"));
If I want to store the template in a database, can it be implemented? The answer is yes. Here you can use Stringtemplateloader to load the template content. The main code implementations are as follows:
Configuration cfg = new configuration ();
Stringtemplateloader Stringloader = new Stringtemplateloader ();
String templatecontent= "Hello ${name}!";
Stringloader.puttemplate ("MyTemplate", TemplateContent);
Cfg.settemplateloader (Stringloader);
Template template = Cfg.gettemplate ("MyTemplate", "utf-8");

Freemarker Error Handling Scheme

Freemarker file If there is an error, the site's front page will report a very obvious error-the brown background, blood-red text, very detrimental to the user experience. How to modify this problem?
You first need to add the following line of code to the Struts.xml configuration file:

1 <constant name= "struts.freemarker.manager.classname" value=" Net.swiftlet.freemarker.MyFreemarkerManager " />

Then create the new Myfreemarkermanager class as follows:

123456789101112131415161718192021222324 public class myfreemarkermanager extends org. Apache. Struts2. Views. Freemarker. Freemarkermanager {    private static final logger log = loggerfactory. Getlogger (myfreemarkermanager.class Public void init(servletcontext servletcontext) throws Templateexception     { config = createconfiguration(servletcontext); config. Settemplateexceptionhandler(templateexceptionhandler. Ignore_handler); contentType = default_content_type; wrapper = createobjectwrapper(servletcontext); if (LOG. isdebugenabled())         { LOG. Debug("Using object Wrapper of Class" + wrapper. GetClass(). GetName());         } config. Setobjectwrapper(wrapper); templatepath = servletcontext. Getinitparameter(initparam_template_path); if (templatepath = = null)        { templatepath = servletcontext. Getinitparameter("TemplatePath");         } configuretemplateloader(createtemplateloader(servletcontext, TemplatePath )); loadsettings(servletcontext);     }}

Freemarker Common Skills (iii)

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.