freemaker宏的用法
freemaker宏
定义:定义一个标签,标签体中可以包含参数,开始标签和结束标签可以包含内容,内容中可以通过${}方式引用标签体中定义的参数
用法:页面引入标签,通过标签可以直接输出标签的内容
HelloWorld实现
定义html.ftl:
<#macro html title> <html> <head> <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" /> </head> <body> <#nested/> </body> </html> </#macro>
用法: <#import "/WEB-INF/template/common/common.ftl" as c> <@c.html title="OA"> 你的内容 </@c.html>
输出结果: <#macro html title> <html> <head> <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" /> </head> <body> 你的内容 </body> </html> </#macro>
相关语法
1.macro
<#macro name param1 param2 ... paramN>
用例 <#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"/>
输出
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
2.nested(<#macro name param1 param2 ... paramN;x y z> )xyz为nested 标签定义的内容,nested 相当于标签内容的占位符
<#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>
输出
1. 0.5
2. 1
3. 1.5
4. 2 Last!
3.循环
<#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"/>
输出结果 <p>Animals: <ul> <li>Mouse <li>Elephant <li>Python </ul>
参考链接