Freemarker Learning Notes (i) Preliminary understanding of Freemarker templates

Source: Internet
Author: User
Tags reserved scalar

*******************************************************

* Reprint Please specify source address Http://blog.csdn.net/csuliky Author: Abu

*******************************************************

First of all, we have a little bit of an understanding of Freemarker, in this chapter, we have to learn how to write a simple but very effective freemarker template.

1. Template + data Model = Output

Suppose one of your electronic store applications needs an HTML page, similar to this one:

We say that the username ("Big Joe") should depend on the logged-in person who accesses the Web page, that the latest product should come from the database and that it will be updated at any time, in which case it is not possible for you to enter the user name, URL or latest product in this HTML page, Because you can't use static HTML pages.

Freemarker's solution to this problem is to use templates (template) instead of static HTML pages. Templates are the same as static HTML pages except that they use the freemarker command to make them dynamic:

Templates are stored on Web servers, often like static HTML pages. But whenever you visit this page, Freemarker will be in time to pass the ${...} Replace it with the latest content to convert the template to a normal HTML page (for example, replace ${user} with "Big Joe" or any user who accesses the page) and send the results to the visitor's browser. This way, the visitor's browser will receive an HTML page like the one in the first example (for example, an HTML page with no Freemarker description), and the user will not feel that the server is actually using Freemarker. During this time, the template is still on the server and there is no change, and when someone accesses the page again, Freemarker will execute it again to ensure that the information displayed on the page is always up to date. Now you may have noticed that the template does not contain any commands to discover who the current audience is, or to connect to the database to query for the latest product. It looks as if it already knows these values. And that's really the case. Freemarker has an important idea (in fact, in MVC) that the display logic and business logic should be separated. In the template you just deal with visual problems, that is, visual design problems, format problems. The data displayed (for example, user name, and so on) is prepared outside the freemarker. Usually the Java language or other common target language. The creator of the template does not need to know how the data is calculated. In fact, when the template is not made any changes, the data can be completely changed, and the appearance of the page may also change. This separation is especially useful when the template designer and the program designer are separated. Freemarker (template designer) is not interested in the calculation of data, but Freemarker must know what the actual data is. The data to be used by all templates will be packaged in a data model. The data was created by the program designer you just mentioned. The template designer is concerned with the data being like a tree structure (like the directories and files on your hard disk), as follows:

(root) | +-user = "Big Joe" | +-Latestproduct | +-url = "products/greenmouse.html" | +-name = "Green Mouse"

Compare this to the ${user} and ${lastestproduct.name} in the template you saw earlier. You can infer that the data model is like a computer system: a root path and a lastestproduct directory, and the URL is the file in the Lastestproduct directory.

Summary: Freemarker requires templates and data models to generate output files (usually HTML files).

2. Data Model Overview

As you can see, the data model is basically a tree. This tree can be very complex and deep, for example:

(root) | +-Animals | | | +-Mouse | | | | +-size = "small" | | | | +-Price = 50 | | | +-Elephant | | | | +-size = "Large" | | | | +-Price = 5000 | | | +-Python | | | +-size = "Medium" | | | +-Price = 4999 | +-test = "It is a test" | +-Whatnot | +-because = "don ' t Know"

A variable as a directory is called a hash table. A hash table stores the query name of another variable (for example: "Animals", "mouse", or "price"). A variable that stores a single value is called a scalar. When you want to use a child variable in a template, you specify its path from the root, and each level uses the "." Apart. To access Price's mouse, you start at the root, enter the animals, then enter the mouse, and finally enter price. So you have to write "Animals.mouse.price". When you will ${...} When placed around an expression like this, you are telling Freemarker to output the corresponding text at this point. There is another kind of important variable: sequences (Sequence). They are similar to hash tables, but they cannot store the names of the variables they contain. Instead, they store the child variables sequentially, which you can access using a numeric index. For example: In this data model, animals and whatnot.fruits are sequences:

(root) | +-Animals | | | +-(1st) | | | +-name = "Mouse" | | | | +-size = "small" | | | | +-Price = 50 | | | +-(2nd) | | | +-name = "Elephant" | | | | +-size = "Large" | | | | +-Price = 5000 | | | +-(3rd) | | | +-name = "Python" | | | +-size = "Medium" | | | +-Price = 4999 | +-Whatnot | +-Fruits | +-(1st) = "Orange" | +-(2nd) = "Banana"

In order to access the child variables of a sequence, you can use a numeric index in square brackets. The index starts at 0, so the first item in the index is 0, and the second is 1, and so on. So in order to visit the first animal, you have to write "Animals[0].name", in order to visit the "whatnot.fruits" of the second item, it is necessary to write "Whatnot.fruits[1". Scalars can be further divided into these classifications:

String: Text, which is any sequence of characters, such as "M" Above, "O", "U", "S", "E". For example: Name, size is string.

Number: Is the value of numbers, like the price above. Note that "50" and 50 are completely different in freemarker. The former is a string, and the latter is a number.

Date/time: Time or date.

Boolean: Value is: True/false (can also be yes/no, or On/off). Like the "protected" sub variable above, it means that the animal is protected.

Summarize:

The image of the data model is called a tree.

A scalar stores a single value. Can be a string, number, date/time, or a Boolean value.

A hash table is a container for storing other variables, and these variables are associated with one of their found names.

A sequence is a container in which other variables are stored sequentially, and a numeric index is used to find the values. The numeric index begins with 0.

3. Template List

The simplest template is an HTML file (or plain text file--freemarker is not limited to HTML). When the client accesses that page, Freemarker sends the HTML page to the client as-is. However, if you want to make the page more dynamic, then you want to start adding special parts that Freemarker can parse into the HTML page:

${: Freemarker will replace the object in the curly braces with the actual value at the time of the output. This is called interpolation (interpolation ).

FTL Tags (Freemarker Template Language tags): FTL (freemarker Template Markup Language) is somewhat similar to HTML markup, but FTL is a freemarker directive and is not printed on output. The FTL tag begins with "#". (The user-defined FTL tag replaces "#" with "@", but this is part of the advanced topic)

Comments: Freemarker annotations are similar to HTML annotations, but are qualified by <#--and-->. Content that includes delimiters between delimiters is freemarker ignored and is not written out again.

Any FTL mark, interpolation, or annotation will be treated as static text in Freemarker and will not be interpreted by freemarker, but only as output. FTL tags what you call the directive is the same as the relationship between HTML tags and HTML tags and HTML elements (such as the:<table> element). (If you can't distinguish FTL marks from freemarker instructions, consider them synonyms.) ) Directive Example

Although Freemarker has a lot of instructions, in the overview, we only introduce three commonly used. if Directive

Using the IF directive, you can skip a section of the template conditionally, assuming that in the following example you would like to greet your boss, Big Joe, to be different from other users:

Here you tell Freemarker "when the user value is" Big Joe ", add", our beloved leader ". The contents of the,< #if condition > and </#if > are skipped when the IF condition is false. Let's elaborate on the conditions used here: "= =" is an operator used to test whether its left and right values are equal, and to return a value of true or false. On the left side of "= =", I refer to the syntax of a variable that should already be very familiar and will be replaced with the value of the variable. In general, the words that are generated in the instruction or interpolation are the variables mentioned. To the right I have specified a string. The strings in the template must always be enclosed in quotation marks. The following will print "Pythons are free today!" and add their price to 0:

< #if Animals.python.price = = 0> Pythons are free today! </#if >

Specified earlier as a string, which is specified directly here (0). Please note that numbers cannot be caused. If you enclose it in quotation marks ("0"), then the Freemarker is misinterpreted as a string:

< #if animals.python.price!= 0> pythons are not free today! </#if >

As you can guess, "!=" is not equal to meaning. You can also write this:

< #if Animals.python.price < animals.elephant.price> pythons are cheaper than elephants today. </#if >

Using the < #else > tag, you can specify what to do if the IF condition is false. For example:

< #if Animals.python.price < animals.elephant.price> pythons are cheaper than elephants today. < #else > Pythons are not cheaper than elephants today. </#if >

This will print ' Pythons are cheaper than elephants today. ', the price of adding a python is lower than the price of an elephant, or else it prints out ' pythons are not cheaper to than elephants today. ''。 If you have a Boolean value (true/false) variable, then you can use it directly in the IF condition:

< #if animals.python.protected> warning! Pythons are protected animals! </#if > list Directive

When you want to list something, list instructions are very late. For example, if you want to merge a template with a previous example (Data-model I used earlier to demonstrate sequences):

<p>we have these animals: <table border=1> <tr><th>name<th>price < #list animals AS Being> <tr><td>${being.name}<td>${being.price} Euros </#list > </table>

The output will be like this:

<p>we have these animals: <table border=1> <tr><th>name<th>price <tr><td> Mouse<td>50 Euros <tr><td>elephant<td>5000 Euros <tr><td>python<td>4999 Euros </table>

Usually the format of the list instruction is as follows:

< #list as a sequence > repeating part of a cyclic variable </#list >

The repeat section will be repeated in each item of the sequence you provide, starting with the first item and one after the other. In all repetitions, the loop variable holds the value of the current item. This variable exists only in the < #list ...> and </#list > tags. As another example, we list the fruit in the data model:

<p>and BTW We have fruits: <ul> < #list whatnot.fruits as fruit> <li>${fruit} </#list > <ul>

Whatnot.fruits expressions should be familiar to you. include Directives

You can insert another file in the template by using the include directive. Suppose you have to display the same copyright logo on many pages, you can create a file that contains the copyright logo and insert it where you want it to appear. For example, you keep the copyright logo in copyright_footer.html:

Any time you need it, you can simply insert it with the include directive:

And the output is as follows:

If you change the copyright_footer.html file, the visitor will see the new copyright notice on all the pages. Integrated Use Instructions

You can use instructions more than once on a page, and you can nest the Freemarker instructions like nested HTML elements. For example, this will list all the animals and use the large font size to print the animal's name:

<p>we have these animals: <table border=1> <tr><th>name<th>price < #list animals AS Being> <tr> <td> < #if being.size = "large" ><font size= "+1" ></#if > ${being.name} <# If being.size = "large" ></font></#if > <td>${being.price} Euros </#list > </table>

Note that because Freemarker does not explain external FTL tags, interpolation, and annotations, it understands the severity of the font label nesting above. processing A variable that cannot be found

In fact, some parameters are often optional in the data model. It is found that people make typical mistakes, and if a variable cannot be found, it will not allow the reference variable to be lost unless you explicitly tell Freemarker how to handle it. Here, we will show two examples of the most typical ways.

Note For programmers: a nonexistent variable and a null variable are the same for freemarker, so "can't find" covers both of these situations.

Wherever you refer to variables, you can use the "!" and default values to specify a default value when a variable is not found. As in the following example, when user is not found in the data model, the template assumes that the user's value is "Anonymous":

! " Anonymous "

}!

Do you add the words "??" after the name of the variable. That means you can't find it. Combined with this and already introduced if instructions you can skip the whole greeting if the user variable is not found:

user??

>

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.