Freemarker syntax with small examples

Source: Internet
Author: User
Tags locale reserved tld

Freemarker syntax with demo version

1 Concepts

2 Instructions

If, else, ElseIf

switch, case, default, break

List, break

Include

Import

Compress

Escape, Noescape.

Assign

Global

Setting

Macro, nested, return.

T, LT, RT

3 Some common methods or precautions

Expression Conversion Class

Digital loops

fetching integers on floating-point

Give a variable a default value

Determine if the object is null

Common formatting dates

To add a global shared variable data model

Ways to call Java objects directly

String handling (built-in method)

Initialize sequences and hashes in the template

Annotation Flags

Sequences Built-in method

Hashes Built-in method

4 Freemarker Considerations in Web Development

Several common objects in the Web

Search order for values in view

Use tags in FTL in templates

How to initialize a shared variable

Integrated configuration with WebWork

5 Advanced methods

Custom Methods

Custom Transforms

End of directory

1 Concepts

The 3 most commonly used concepts

Sequence sequence, corresponding to a list of Java, array and other non-key pairs of sets

A collection of hash key-value pairs

Namespace a reference to a FTL file that allows access to the resources of the FTL file

2 Instructions

If, else, ElseIf

Grammar

< #if condition>

...

< #elseif condition2>

...

< #elseif condition3>

...

...

< #else >

...

</#if >

Case

< #if x = 1>

X is 1

</#if >

< #if x = 1>

X is 1

< #else >

X is not 1

</#if >

switch, case, default, break

Grammar

< #switch value>

< #case refvalue1>

...

< #break >

< #case refvalue2>

...

< #break >

...

< #case refvaluen>

...

< #break >

< #default >

...

</#switch >

Case

String

< #switch being.size>

< #case "small" >

This'll be processed if it is small

< #break >

< #case "Medium" >

This'll be processed if it is medium

< #break >

< #case "large" >

This'll be processed if it is large

< #break >

< #default >

This'll be processed if it is neither

</#switch >

Digital

< #switch x>

< #case x = 1>

1

< #case x = 2>

2

< #default >

D

</#switch >

If X=1 output 1 2, x=2 output 2, x=3 output D

List, break

Grammar

< #list sequence as item>

...

< #if item = "Spring" >< #break ></#if >

...

</#list >

Key words

Item_index: Is the subscript for the list's current value

Item_has_next: Determine if the list still has a value

Case

< #assign seq = ["Winter", "Spring", "Summer", "Autumn"]>

< #list seq as x>

${x_index + 1}. ${x}< #if x_has_next>,</#if >

</#list >

Output

1. Winter,

2. Spring,

3. Summer,

4. Autumn

Include

Grammar

< #include filename>

Or

< #include filename options>

Options contain two properties

encoding= "GBK" encoding format

Whether Parse=true is parsed as a FTL syntax, the default is that True,false is introduced in text. Note that FTL file Ribourg values are directly assigned such as Parse=true instead of parse= "true"

Case

/COMMON/COPYRIGHT.FTL contains content

Copyright 2001-2002 ${me}<br>

All rights reserved.

Template file

< #assign me = "Juila Smith" >

<p>yeah.

< #include "/COMMON/COPYRIGHT.FTL" encoding= "GBK" >

Output results

<p>yeah.

Copyright 2001-2002 Juila Smith

All rights reserved.

Import

Grammar

< #import path as hash>

Like the import in Java, it imports the file, and then it can use the macro component in the file being imported in the current file

Case

Assuming that the MYLIB.FTL defines the macro copyright, then we can use this in other template pages

< #import "/LIBS/MYLIB.FTL" as my>

< @my. Copyright date= "1999-2002"/>

"My" is called namespace in Freemarker.

Compress

Grammar

< #compress >

...

</#compress >

Lines used to compress white space and whitespace

Case

< #assign x = "moo \ n" >

(< #compress >

1 2 3 4 5

${moo}

Test only

I said, test only

</#compress >)

Output

(1 2 3 4 5

Moo

Test only

I said, test only)

Escape, Noescape.

Grammar

< #escape identifier as expression>

...

< #noescape >...</#noescape >

...

</#escape >

Case

The main use of similar string variable output, such as a module of all string output must be HTML security, this time you can use the expression

< #escape x as x?html>

The name: ${firstname}

< #noescape >last Name: ${lastname}</#noescape >

Maiden Name: ${maidenname}

</#escape >

Same expression

The name: ${firstname?html}

Last Name: ${lastname}

Maiden Name: ${maidenname?html}

Assign

Grammar

< #assign name=value>

Or

< #assign name1=value1 name2=value2 ... namen=valuen>

Or

< #assign same as above ... in namespacehash>

Or

< #assign name>

Capture this

</#assign >

Or

< #assign name in namespacehash>

Capture this

</#assign >

Case

Generate variables, and assign values to variables

Assign a sequence value to seasons

< #assign seasons = ["Winter", "Spring", "Summer", "Autumn"]>

Give the variable test plus 1.

< #assign test = test + 1>

Give my namespage a variable bgcolor, and you can access this variable by My.bgcolor

< #import "/MYLIB.FTL" as my>

< #assign bgcolor= "Red" in my>

Save a section of output text as a variable in X

The text in the shaded section below will be assigned to X

< #assign x>

< #list 1..3 as n>

${n} < @myMacro/>

</#list >

</#assign >

Number of words: ${x?word_list?size}

${X}

< #assign X>hello ${user}!</#assign > Error

< #assign x= "Hello ${user}!" > True

It also supports Chinese assignments, such as:

< #assign grammar >

Java

</#assign >

${syntax}

Print output:

Java

Global

Grammar

< #global name=value>

Or

< #global name1=value1 name2=value2 ... namen=valuen>

Or

< #global name>

Capture this

</#global >

Global assignment syntax, which uses this syntax to assign a value to a variable, so this variable is visible in all namespace if the variable is overwritten by the current assign syntax such as < #global x=2> < #assign x=1> in the current page x= 2 will be hidden, or accessed via ${.global.x}

Setting

Grammar

< #setting name=value>

An environment used to set up the entire system

Locale

Number_format

Boolean_format

Date_format, Time_format, Datetime_format

Time_zone

Classic_compatible

Case

If the current is Hungarian setting, then modify it into the United States

${1.2}

< #setting locale= "en_US" >

${1.2}

Output

1,2

1.2

Because Hungary is using "," as the decimal separator, the United States is using "."

Macro, nested, return.

Grammar

< #macro name param1 param2 ... paramn>

...

< #nested loopvar1, Loopvar2, ..., loopvarn>

...

< #return >

...

</#macro >

Case

< #macro test foo bar= "Bar" baaz=-1>

Test text, and the params: ${foo}, ${bar}, ${baaz}

</#macro >

< @test foo= "a" bar= "B" baaz=5*5-2/>

< @test foo= "a" bar= "B"/>

< @test foo= "a" baaz=5*5-2/>

< @test foo= "a"/>

Output

Test text, and the params:a, B, 23

Test text, and the params:a, B,-1

Test text, and the Params:a, Bar, 23

Test text, and the Params:a, Bar,-1

Macros that define circular output

< #macro list title items>

<p>${title?cap_first}:

<ul>

< #list items as x>

<li>${x?cap_first}

</#list >

</ul>

</#macro >

< @list items=["mouse", "elephant", "python"] title= "Animals"/>

Output results

<p>animals:

<ul>

<li>mouse

<li>elephant

<li>python

</ul>

Macros that contain body

< #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 >

<% @page contenttype= "text/html;charset=iso-8859-2" language= "java"%>

<% @taglib uri= "/web-inf/struts-html.tld" prefix= "html"%>

<% @taglib uri= "/web-inf/struts-bean.tld" prefix= "Bean"%>

<body>

Keyword:

Exclude:

</body>

Template FTL Page

< #assign html=jsptaglibs["/web-inf/struts-html.tld"]>

< #assign bean=jsptaglibs["/web-inf/struts-bean.tld"]>

<body>

< @html .errors/>

< @html. form action= "/query" >

Keyword: < @html. text property= "Keyword"/><br>

Exclude: < @html. text property= "Exclude"/><br>

< @html. Submit value= "Send"/>

</@html .form>

</body>

How to initialize a shared variable

1. Initializing a global shared data model

Freemark support for the initialization of shared data when used on the web is not sufficient to be implemented at the time of configuration initialization, and global variables must be initialized through FTL files. This is not a full demand, we need to set aside an interface to initialize the shared data of the system at the time of servlet Init

specific to and webwork integration, because itself WebWork provides a consolidation servlet, if you want to increase global share variables, you can modify the Com.opensymphony.webwork.views.freemarker.FreemarkerServlet to implement, we can initialize the global shared variable when this servlet initializes

Integrated configuration with WebWork

Configure Web.xml

<servlet>

<servlet-name>freemarker</servlet-name>

<servlet-class>com.opensymphony.webwork.views.freemarker.FreemarkerServlet</servlet-class>

<init-param>

<param-name>TemplatePath</param-name>

<param-value>/</param-value>

<!-template loading folder, where relative to the context root, recursively get all the templates under the folder-->

</init-param>

<init-param>

<param-name>NoCache</param-name> <!-the template cache-->

<param-value>true</param-value>

</init-param>

<init-param>

<param-name>ContentType</param-name>

<param-value>text/html</param-value>

</init-param>

<init-param>

<param-name>template_update_delay</param-name>

<!-template update time, 0 means update every time, this is suitable for development time-->

<param-value>0</param-value>

</init-param>

<init-param>

<param-name>default_encoding</param-name>

<param-value>GBK</param-value>

</init-param>

<init-param>

<param-name>number_format</param-name>

<param-value>0.##########</param-value><!-Digital display Format-->

</init-param>

<load-on-startup>1</load-on-startup>

</servlet>

<servlet-mapping>

<servlet-name>freemarker</servlet-name>

<url-pattern>*.ftl</url-pattern>

</servlet-mapping>

5 Advanced methods

Custom Methods

${timer ("Yyyy-mm-dd h:mm:ss", X)}

${timer ("Yyyy-mm-dd", X)}

In addition to being able to invoke the method outside the object (${object.methed (args)}) in the template, you can directly invoke the Java implementation method, and the Java class must implement an interface Templatemethodmodel method, exec (List args). Here is an example of how to convert milliseconds to a format-by-output time

public class Longtodate implements Templatemethodmodel {

Public Object exec (List args) throws Templatemodelexception {

SimpleDateFormat mydate = new SimpleDateFormat ((String) args.get (0));

Return Mydate.format (New Date (Long.parselong ((String) Args.get (1));

}

}

To put a Longtodate object into the data model

Root.put ("Timer", new Indexofmethod ());

Used in FTL templates

< #assign x = "123112455445" >

${timer ("Yyyy-mm-dd h:mm:ss", X)}

${timer ("Yyyy-mm-dd", X)}

Output

2001-10-12 5:21:12

2001-10-12

Custom Transforms

Implements a Custom < @transform > text or expression </@transform > Functionality that allows parsing of the final text in the middle

Example: Implementation < @upcase >str</@upcase > The ability to convert STR to STR

The code is as follows:

Import java.io.*;

Import java.util.*;

Import Freemarker.template.TemplateTransformModel;

Class Uppercasetransform implements Templatetransformmodel {

Public Writer getwriter (Writer out, Map args) {

Return to New Uppercasewriter (out);

}

Private class Uppercasewriter extends Writer {

Private Writer out;

Uppercasewriter (Writer out) {

This.out = out;

}

public void Write (char[] cbuf, int off, int len)

Throws IOException {

Out.write (New String (Cbuf, off, Len). toUpperCase ());

}

public void Flush () throws IOException {

Out.flush ();

}

public void Close () {

}

}

}

Then put this object into the data model

Root.put ("UpCase", New Uppercasetransform ());

You can use the following in the view (FTL) page

< @upcase >

Hello World

</@upcase >

Print output:

HELLO World

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.