Use of Freemarker macro (macro)

Source: Internet
Author: User

Some people say that with freemarker, but there is no use of its macros (macro), it is not really used freemarker. Is that the macro is a major feature of Freemarker.

The definition of a macro can be seen in the relevant document, which is clearly described in the following, a look at its usage.

/WEB-INF/TEMPLATE/COMMON/COMMON.FTL:

< #macro HTML title>
<meta http-equiv= "Content-type" content= "text/html; CHARSET=GBK "/>
<title>${title}</title>
<link rel= "stylesheet" rev= "stylesheet" href= "/oa/file/css.css" type= "Text/css" media= "All"/>

<body>
< #nested/>
</body>

</#macro >

Then define in Freemarker.properties:
AUTO_IMPORT=/WEB-INF/TEMPLATE/COMMON/COMMON.FTL as C

And then the other FTL files are ready to use it.

TEST.FTL:
<@c.html title= "OA" >
Your content
</@c.html>

If not defined in Freemarker.properties, you can include this FTL in each file:
< #import "/WEB-INF/TEMPLATE/COMMON/COMMON.FTL" as c>

Different occasions have different use. If used well, it will greatly save your development time.


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

Define a macro for looping 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>

Macro that contains 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 >
</@repeat >

Output

1.0.5
2.1
3.1.5
4.2 last!

--------------------------------------------------------------------------------

Notice when you use it: Don't forget the double quotes.

< #import "/PAGELIBS/BOOK.FTL" as book>

< @workorder. Price value= "${book.price}"/>


Macros macro
Macros are defined in templates using macro directives

L.1 Basic Usage

A macro is a template fragment associated with a variable so that it can be used with user-defined directives in the template, and here's an example:

< #macro greet> <font size= "+2" >hello joe!</font></#macro >
When a macro is called, it is similar to other directives that use Freemarker, except that @ replaces # in the FTL tag.

< @greet ></@greet > <#--< @greet/>-->
In the macro directive, you can define parameters after the macros variable, such as:

< #macro greet person> <font size= "+2" >hello ${person}!</font></#macro >
You can use this macro variable in this way:

< @greet person= "Fred"/>
But the following code has a different meaning:

< @greet person=fred/>
This means that the value of the Fred variable is passed to the person parameter, which is not only a string, but also other types, even complex expressions.

Macros can have multiple parameters, here is an example:

< #macro greet person color> <font size= "+2" color= "${color}" >hello ${person}!</font></#macro >
You can use the macro variable in this way, where the order of the arguments is irrelevant:

< @greet person= "Fred" color= "Black"/>
You can specify a default value when defining a parameter, otherwise you must assign values to all parameters when calling a macro:

< #macro greet person color= "BLACK" > <font size= "+2" color= "${color}" >hello ${person}!</font></# Macro>
Note: The macro parameter is a local variable and can only be valid in the macro definition.

Nested content
Freemarker macros can have nested content,< #nested > directives execute a template fragment between the start and end tags of a macro invocation instruction, for a simple example:

< #macro border> <table border=4 cellspacing=0 cellpadding=4><tr><td> < #nested > </td& gt;</tr></table></#macro >
To perform a macro call:

< @border >the bordered text</@border >


Output Result:

<table border=4 cellspacing=0 cellpadding=4><tr><td> the bordered text </td></tr></ Table>


< #nested > instructions can be called multiple times, and the same content is executed each time.

< #macro do_thrice> < #nested > < #nested > < #nested ></#macro >< @do_thrice > anything. </@do_thrice >


FMPP Output Results:

Anything.Anything.Anything.


Nested content can be a valid FTL, here is a somewhat complicated example, we combine the above three macros:

< @border > <ul> < @do_thrice > <li>< @greet person= "Joe"/> </@do_thrice > </ul> </@border >


Output Result:

<table border=4 cellspacing=0 cellpadding=4><tr><td> <ul> <li><font size= "+2" > Hello joe!</font><li><font size= "+2" >hello joe!</font><li><font size= "+2" > Hello joe!</font></ul></tr></td></table>


Local variables in a macro definition are not visible to nested content, for example:

< #macro repeat count> < #local y = "Test" > < #list 1..count as x> ${y} ${count}/${x}: < #nested > & lt;/#list ></#macro >< @repeat count=3>${y?default ("?")} ${x?default ("?")} ${count?default ("?")} </@repeat >


Output Result:

Test 3/1:???? Test 3/2:???? Test 3/3:???


Using a loop variable in a macro definition
The nestted directive can also have a loop variable (the meaning of the loop variable is shown in the next section), and when the macro is called, the name of the loop variable is listed in the following order, formatted as follows:

<@ macro_name paramter list; Loop variable list[,]>


For example:

< #macro repeat count> < #list 1..count as x> < #nested x, X/2, x==count> </#list ></#macro >& lt; @repeat count=4; C, HALFC, Last> ${c}. ${halfc}< #if last> last!</#if ></@repeat >


Here count is the parameter of the macro, C, Halfc,last is the loop variable, the output result:

1.0.5 2. 1 3. 1.5 4. 2 last!


There is no problem with the difference between the loop variable and the macro tag, and the extra value is not visible if a loop variable is specified less than the call. A loop variable is specified at the time of invocation, and the extra loop variable is not created:

< @repeat count=4; C, HALFC, Last> ${c}. ${halfc}< #if last> last!</#if ></@repeat >< @repeat count=4; C, halfc> ${c}. ${halfc}</@repeat >< @repeat count=4> Just repeat it...</@repeat >
Defining variables in Templates
There are three types of variables defined in the template:

Plain variables: can be accessed anywhere in the template, including templates inserted using the include directive, created and replaced with assign directives.
Local variables: Valid in the macro definition body, created and replaced with local directives.
Loop variable: A nested content that can exist only in a directive, created automatically by an instruction (such as list); A macro's argument is a local variable, not a loop variable
A local variable hides (rather than overwrites) a plain variable with the same name, and the loop variable hides local and plain variables with the same name, and here's an example:

< #assign x = "plain" >${x} <#--we see the plain var. here-->< @test/>6. ${X} <#--The value of plain var. is not changed-->< #list ["Loop"] as x> 7. ${X} <#--now the loop var. hides the plain var.-< #assign x = "plain2" > <#--replace the Plain Var, Hiding does not mater--8. ${X} <#--It still hides the plain var.--></#list >9. ${X} <#--The new value of plain var.-->< #macro test> 2. ${X} <#--We still see the plain var. here-< #local x = "local" > 3. ${X} <#--now the local var. hides it-< #list ["loop"] as x> 4. ${X} <#--now the loop var. hides the local var.-</#list > 5. ${X} <#--Now we see the local var. again--></#macro >
Output Result:

1. Plain 2. Plain 3. Local 4. Loop 5. Local 6. Plain 7. Loop 8. Loop 9. Plain2
Internal loop variables Hide external loop variables with the same name, such as:

< #list ["Loop 1"] as x> ${x} < #list ["Loop 2"] as x> ${x} < #list ["Loop 3"] as x> ${x} < ;/#list > ${x} </#list > ${x}</#list >
Output Result:

Loop 1 Loop 2 loop 3 loop 2 Loop 1
Variables in the template hide (rather than overwrite) the same name variable in the data model, and if you need to access a variable with the same name in the data model, use the special variable global, the following example assumes that the value of user in the data model is big JOE:

< #assign user = "Joe hider" >${user} <#--prints:joe hider-->${.globals.user} <#--prints:big Jo E--
Name space
Typically, only one namespace is used, called the primary namespace, but in order to create a collection of reusable macros, converters, or other variables (often called libraries), you must use a multi-namespace, which is designed to prevent conflicting names with the same name

Create a library
The following is an example of creating a library (assuming that it is saved in LIB/MY_TEST.FTL):

< #macro copyright Date> <p>copyright (C) ${date} Julia Smith. All rights reserved. <br>email: ${mail}</p></#macro > < #assign mail = "[Email Protected]" >
Importing a library into a template using the import directive, Freemarker creates a new namespace for the imported library and can access the variables in the library through the hash variable specified in the import directive:

< #import "/LIB/MY_TEST.FTL" as my>< #assign mail= "[email protected]" >< @my. Copyright date= " 1999-2002 "/>${my.mail}${mail}
Output Result:

<p>copyright (C) 1999-2002 Julia Smith. All rights reserved. <br>email: [email protected]</p>[email protected]@acme. com
You can see that the two variable names used in the example do not conflict because they are in different namespaces. You can also use the Assign directive to create or override variables in an imported namespace, as an example:

< #import "/LIB/MY_TEST.FTL" as my>${my.mail}< #assign mail= "[email protected]" in My>${my.mail}
Output Result:

[email protected]@other. com
Variables in the data model are visible anywhere, and include different namespaces, and the following are the modified libraries:

< #macro copyright Date> <p>copyright (C) ${date} ${user}. All rights reserved.</p></#macro >< #assign mail = "${user} @acme. com" >
Assuming that the value of the user variable in the data model is Fred, the following code:

< #import "/LIB/MY_TEST.FTL" as my>< @my. Copyright date= "1999-2002"/>${my.mail}
Output Result:

<p>copyright (C) 1999-2002 Fred. All rights Reserved.</p>[email protected]
Choose velocity or Freemarker?
Velocity is another excellent template engine, it is a strong competitor of Freemarker. But its template language is not strong enough, nor rigorous enough.

In addition to the powerful functions that freemarker built within velocity, Freemarker is better at the following:

Freemarker's division of Performance Logic and business logic is more stringent than velocity, and freemarker does not allow direct manipulation of the servlet API in the template (and velocity can), such as Freemarker Direct access to the HttpServletRequest object is prohibited (but can be accessed in the HttpServletRequest object attribute). With a more restrictive isolation mechanism, operations involving logical processing are forced to be transferred to the logical layer. So that the clarity between the levels is fully ensured.

Another feature that velocity cannot implement is the most practical feature: Freemarker provides a powerful macro.

In addition, Freemarker provides good support for JSP tag. We can consider freemarker as a JSP page that allows only tag (in fact, the expression syntax of Freemarker is very similar to El Syntax). From the point of view of development, only JSP pages that are allowed to use tag, have largely ensured the separation of the page representation logic from the business logic. Programmers in JSP script mixed logic code, mostly for lazy, as long as it is not possible to write Java code in the page template directly, I believe the programmer will not specifically write a JSP tag to deliberately violate the principle of hierarchical division.

Use of Freemarker macro (macro)

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.