FreeMarker note Chapter 3 Template, freemarker chapter 3

Source: Internet
Author: User

FreeMarker note Chapter 3 Template, freemarker chapter 3

First, let's have a dozen white rabbits;

3.1 Overall Structure

A program written in a language is a template, and the template is also FTL (representing the FreeMarker template language ).

The template is composed of the following parts:

FTL is case sensitive;

FTL tags cannot be used in other FTL tags and interpolation. The following is an error;

<#if <#include 'foo'>='bar'>...</#if>

Annotations can be placed in the middle of FTL tags and interpolation; 3.2 instructions

There are two types of labels:

  • Start Tag: <# directivename parametes>
  • End Tag:

There are two types of commands: pre-defined commands and user-defined commands. Use @ to replace user-defined commands #; 3.3 expression 3.3.1 Introduction

$ {Expression} 3.3.2 Quick View (memo sheet)

Here is a reminder for people who have already known FreeMarker or experienced programmers:

3.3.3 directly determine the value 3.3.3.1 string

Escape

${"It's \"quoted\" and this is a blackslash: \\"}

Output:

It's "quoted" and this is a blackslash: \

List of turn orders:

The hexadecimal code must be 1-4 bits. In the following example, the copyright symbols "\ xA9", "\ x0A9", and "\ x00A9" are all placed in the string ";

A special string is a native string. In Native strings, The backslash and $ {do not have any special meaning. They are considered normal characters. To indicate that the string is a native string, place the letter r before the start quotation marks or single quotation marks;

${r"${foo}"}${r"C:\foo\bar"}

Will print:

${foo}C:\foo\bar
Instance
<Ul> <li> escape: $ {"It's \" quoted \ "and this is a blackslash :\\"} </li> <li> copyright: $ {"\ xA9 1999-2000"} </li> <li> native string: $ {r "$ {foo}"} </li> </ul>

Output:

3.3.3.2 numbers

Scientific note is currently not supported (1E3 is wrong ). Do not enter 0 before the decimal point (. 5 is also incorrect); 3.3.3.3 Boolean Value

Write true or false directly to indicate a Boolean value; 3.3.3.4 Sequence

Specify the sequence of a text, use commas to separate each sub-variable, and place the entire list in square brackets.

<#list ["winter", "spring", "summer", "autumn"] as x>${x}</#list>

The output is as follows:

winterspringsummerautumn

If the project in the list is an expression, you can also do this: [2 + 2, [1, 2, 4], "whatnot"], where the first sub-variable is the number 4, the second sub-variable is a sequence, and the third sub-variable is the string "whatnot ".

You can also use start .. end defines the sequence that stores the range of numbers. Here, start and end are used to process numeric value expressions, such as 2 .. 5 and [2, 3, 4, 5] are the same, but using the former will be more efficient (less memory usage and faster ). We can see that the former does not use square brackets. This can also be used to define the decreasing Numerical range, for example, 5 .. 2. (In addition, you can also omit the end, just 5 .., To infinity ). Instance

/FreeMarker-hello-web/src/main/webapp/WEB-INF/ftl/3/list. ftl

    <#assign season=["summer", "winter", "spring", "autumn"]>    <p>        <#list season as s>            ${s},        </#list>    </p>    <p>        <#list season[2..] as x>            ${x},        </#list>    </p>

Output:

summer, winter, spring, autumn, spring, autumn, 
3.3.3.5 hash table

Keys and values appear in pairs and are separated by colons. {"Name": "green mouse", "price": 150}; 3.3.4 retrieves data from the hash table from the top-level variable 3.3.3.4.2.

Book. author. name to read the name of auther;

If we want to specify the sub-variables of the same expression, there is another syntax format: book ["title"].

The following examples have the same meanings:book.author.name, book["author"].name, book.author.["name"], book["author"]["name"].

When the dot syntax is used, the naming of top-level variables is the same (only letters, numbers, underscores, $, @, and so on can be used for naming ), when square brackets are used, there is no such restriction. It can be any expression. (For FreeMarker to support XML, if the variable name is * (asterisk) or **, the square brackets syntax format should be used ). 3.3.4.3 retrieve data from the sequence

Animals [0]. name3.3.4.4 special Variables

Special variables are defined by the FreeMarker engine itself. to use them, you can use the following syntax:. variable_name; 3.3.5 string operations 3.3.5.1 interpolation (or connection) 3.3.3.5.2 to get a character

User [0], assuming the user is "Big Joe", then

${user[0]}${user[4]}

Will print:

BJ

You can use the splitting sequence to obtain characters in a certain range, for exampleUSER[1 .. 4]And{User [4 ..]}. However, this method has been discarded. As an alternative, you can use the built-in function substring. Instance

/FreeMarker-hello-web/src/main/webapp/WEB-INF/ftl/3/string. ftl

<Ul> <li> Read a character: $ {user [0]} </li> <li> Read a certain range of characters: $ {user [1 .. 5] }</li> <li> this operation has been deprecated. Now, use the built-in function substring, $ {user? Substring (1, 5) }</li> </ul>

Output:

• Read a character: B • read a certain range of characters: ig Jo • this operation has been deprecated and now uses the built-in functions substring, ig J
3.3.6 sequential operations 3.3.6.1 connections

Sequence connections can be performed using the + number:

<#list ["Joe", "Fred"] + ["Julia", "Kate"] as user>\- ${user}</#list>

Do not use sequential join operations when many duplicate connections exist, such as appending a project to the sequence in a loop, the reading speed of the sequence generated by many repeated connections in this way will be slow; 3.3.6.2 sequential splitting

Use [firstindex .. lastindex] can be used to obtain a part of the sequence. Here the firstindex and lastindex expressions result in numbers. If seq stores the sequence "a", "B", "c", "d ", "f", then the expression seq [1 .. 4] It will be a sequence containing "B", "c", "d", and "e. Instance

/FreeMarker-hello-web/src/main/webapp/WEB-INF/ftl/3/list. ftl

<H3> sequence operation 
3.3.7 hash table operations 3.3.7.1 join

You can use the plus sign (+) to connect to the hash table.

<#assign ages = {"Joe":23, "Fred":25} + {"Joe":30, "Julia":18}>
3.3.8 arithmetic operations

Modulus (remainder): % 3.3.9 comparison Calculation

Use = (OR =, and the two values are exactly the same.) 3.3.10 logical operation 3.3.11 built-in functions

Built-in functions? Form provides different forms or other information about variables.

For example, obtain the string in uppercase format: user? Upper_case;

Built-in functions used by the string:

  • Html: All Special HTML characters in a string must be replaced by entity references (for example, <instead <).
  • Cap_first: the first letter of the string is in uppercase;
  • Lower_case: lowercase string format;
  • Upper_case: String in upper case;
  • Trim: removes spaces at the beginning and end of a string;

Built-in functions used by sequences:

  • Size: number of elements in the sequence

Built-in functions used by numbers:

  • Int: integer part of a number (for example,-1.9? Int Is-1)

Example:

${test?html}${test?upper_case?html}

The output is:

Tom &amp; JerryTOM &amp; JERRY
3.3.12 method call

Suppose the programmer defines a repeat method that can be called. The first parameter is of the string type, and the second parameter is of the numerical type.

${repeat("What", 3)}

Print:

WhatWhatWhat
3.3.13 process nonexistent values

Note that this operation is available only after FreeMarker2.3.7 (used to replace the built-in functions default, exists and if_exists); 3.3.13.1 default Value

Unsafe_expr! Default_expr or unsafe_expr! Or (unsafe_expr )! Default_expr or (unsafe_expr )!

${mouse!"No mouse."}<#assign mouse="Jerry">${mouse!"No mouse."}

The output is as follows:

No mouse.Jerry

The default value can be an expression of any type or a string.

hits!0;colors!["red", "green", "blue"]

There are no strict restrictions on the Complex Program of the default expression. You can write it like this:

cargo.weight!(item.weight * itemCount+10)

If the default value is ignored, the result will be an empty string, an empty sequence, or an empty hash table.

(${mouse!})<#assign mouse = "Jerry">(${mouse!})

Output:

()(Jerry)

When it is not a top-level variable, the default operator can be either of the following methods:

product.color!"red"

If the color does not exist ("red" is returned), it will be processed. However, if the product does not exist, it will not be processed. That is to say, the product must exist. Otherwise, the template will report an error.

(product.color)!"red"

If the product does not exist or the product does not exist and the color does not exist, the default value "red" is displayed without an error.

The default operation can also act on the sequence, for example:

<#assign seq = ['a', 'b']>${seq[0]!'-'}${seq[1]!'-'}${seq[2]!'-'}${seq[3]!'-'}

Output:

ab\-\-
3.3.13.2 check for nonexistent values

Unsafe_expr ?? Or (unsafe_expr )??

<#if mouse??>    Mouse found<#else>    No mouse found</#if>Creating mouse...<#assign mouse = "Jerry"><#if mouse??>    Mouse found<#else>    No mouse found</#if>

Output:

No mouse foundCreating mouse...Mouse found
3.3.14 parentheses 3.3.15 spaces in expressions

FTL ignores unnecessary spaces in the expression. 3.3.16 operator priority 3.4 Interpolation

 

Project
Freemarker traversal List exception TemplateException template Error

Is your definition incorrect...
<# Assign list1 = ["a", "B"]>
<# List list1! As temp>
$ {Temp}
</# List>
 
In Java programs, how can a freemarker template be made into an editable template?

Thoughts and ideas are the most important
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~
Isn't it about modifying freemarker files?

First, read the file to the textarea of the webpage.
Then, the modified file content is modified.
Rewrite to the template file

Isn't that what it looks like?

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.