• 【FreeMarker】FreeMarker使用(三)


      搭建一个

      1、FreeMarker取值

     1 <!DOCTYPE html>
     2 <html>
     3 <head>
     4 <meta charset="UTF-8">
     5 <title>Insert title here</title>
     6 </head>
     7 <body>
     8     <h1>逻辑</h1>
     9      <div>
    10          1、取基本值
    11          <ul>
    12              <li>整型:${intValue }</li>
    13              <li>字符串:${stringValue }</li>
    14              <li>double型:${doubleValue }</li>
    15              <li>布尔型:${booleanValue }</li>
    16              <li>时间:${dateValue?string('yyyy-MM-dd') }</li>
    17              <li>null值:${nullValue}</li>
    18          </ul>
    19          2、运算
    20          <ul>
    21              <li>加法:${intValue + 100}</li>
    22          </ul>
    23          3、集合
    24           <ul>
    25              List集合
    26              <#list list as item>
    27                  <li>${item}</li>
    28              </#list>
    29              Map集合
    30              <#list map?keys as key>
    31                  <li>${key}:${map[key]}</li>
    32              </#list>
    33          </ul>
    34      </div>
    35 </body>
    36 </html>

      2、逻辑语法

     1 <!DOCTYPE html>
     2 <html>
     3 <head>
     4 <meta charset="UTF-8">
     5 <title>Insert title here</title>
     6 </head>
     7 <body>
     8     <h1>逻辑语法</h1>
     9      <div>
    10          1、if
    11          <ul>
    12              <#assign var=99/>
    13              <#if var == 99 > 
    14                  <li>var=${var }</li>
    15                  
    16              </#if>
    17              
    18              <#assign var1=199/>
    19              <#if var1 == 99 > 
    20                  <li>var1=${var1 }</li>
    21              <#else>
    22                  <li>var1=99</li>
    23              </#if>
    24              
    25              <#assign var2 = 299/>
    26              <#if var2 &lt; 99 > 
    27                  <li>var2 &lt; 99</li>
    28              <elseif var2 == 99 >
    29                  <li>var2 = 299</li>
    30              <#else >
    31                  <li>var2 &gt; 99</li>
    32              </#if>
    33          </ul>
    34          2、switch
    35          <ul>
    36              <#assign var=3/>
    37              <#switch var > 
    38                  <#case 1>
    39                      <li>1</li>
    40                  <#case 2>
    41                      <li>2</li>
    42                      <#break>
    43                  <#case 3>
    44                      <li>3</li>
    45                  <#case 4>
    46                      <li>4</li>
    47                      <#break>
    48                  <#default>
    49                      <li>default</li>
    50              </#switch>
    51          </ul>
    52          
    53      </div>
    54 </body>
    55 </html>

      3、字符串处理

     1 <!DOCTYPE html>
     2 <html>
     3 <head>
     4 <meta charset="UTF-8">
     5 <title>Insert title here</title>
     6 </head>
     7 <body>
     8     <h1>字符串</h1>
     9     <h2>字符串常用内置函数</h2>
    10      <div>
    11          <ul>
    12              <#assign a='hello'/>
    13              <#assign b='world'/>
    14              <br />"+" 加号连接
    15              <li>a + b = ${a + b }</li>
    16              <br />substring 截取
    17              <li>(a + b)?substring(5,8) = ${(a + b)?substring(5,8) }</li>
    18              <br />length 长度
    19              <li>(a + b)?length = ${(a + b)?length }</li>
    20              <br />upper_case 大写
    21              <li>(a + b)?upper_case = ${(a + b)?upper_case }</li>
    22              <br />lower_case 小写
    23              <li>(a + b)?lower_case = ${(a + b)?lower_case }</li>
    24              <br />index_of 位置
    25              <li>(a + b)?index_of('w') = ${(a + b)?index_of('w') }</li>
    26              <br />replace 替换
    27              <li>(a + b)?replace('w', 'W' ) = ${(a + b)?replace('w', 'W') }</li>
    28              <br />contains 包含
    29              <li>(a + b)?contains('w') = ${(a + b)?contains('w') }</li>
    30          </ul>
    31      </div>
    32 </body>
    33 </html>

       4、自定义函数

        a、编写自定义函数方法类

     1 package com.test.freemarker.method;
     2 
     3 import java.math.BigDecimal;
     4 import java.util.Collection;
     5 import java.util.Collections;
     6 import java.util.Comparator;
     7 import java.util.List;
     8 
     9 import freemarker.template.SimpleSequence;
    10 import freemarker.template.TemplateMethodModelEx;
    11 import freemarker.template.TemplateModelException;
    12 
    13 public class SortMethod implements TemplateMethodModelEx{
    14 
    15     @Override
    16     public Object exec(List arguments) throws TemplateModelException {
    17 
    18         // 获取第一个请求参数
    19         // 参数先转freemarker数据类型
    20         SimpleSequence arg0 = (SimpleSequence) arguments.get(0);
    21         List<BigDecimal> list = arg0.toList();
    22         
    23         Collections.sort(list, new Comparator<BigDecimal>() {
    24 
    25             @Override
    26             public int compare(BigDecimal o1, BigDecimal o2) {
    27                 return o1.compareTo(o2);
    28             }
    29         });
    30 
    31         return list;
    32     }
    33 
    34 }

        b、在model中添加方法

    1 @RequestMapping("/customMethod")
    2 public ModelAndView customMethod() {
    3     ModelAndView modelAndView = new ModelAndView("customMethod");
    4     modelAndView.addObject("sort_int", new SortMethod());
    5     return modelAndView;
    6 }

        c、也模板中使用方法

     1 <!DOCTYPE html>
     2 <html>
     3 <head>
     4 <meta charset="UTF-8">
     5 <title>Insert title here</title>
     6 </head>
     7 <body>
     8     <h1>自定义函数</h1>
     9     <h2>字符串常用内置函数</h2>
    10      <div>
    11          <#assign myList=[2,3,4,5,1,8,9,7] />
    12          <br />未排序
    13          <ul>
    14              <#list myList as item >
    15              <li>${item }</li>
    16              </#list>
    17          </ul>
    18          <br />排序(sort_int)
    19          <ul>
    20              <#list sort_int(myList) as item >
    21              <li>${item }</li>
    22              </#list>
    23          </ul>
    24      </div>
    25 </body>
    26 </html>

      5、指令、自定义指令

        a、编辑自定义指令类

     1 package com.test.freemarker.service;
     2 
     3 import java.io.IOException;
     4 import java.util.ArrayList;
     5 import java.util.List;
     6 import java.util.Map;
     7 
     8 import org.springframework.stereotype.Service;
     9 
    10 import freemarker.core.Environment;
    11 import freemarker.template.SimpleSequence;
    12 import freemarker.template.TemplateBooleanModel;
    13 import freemarker.template.TemplateDirectiveBody;
    14 import freemarker.template.TemplateDirectiveModel;
    15 import freemarker.template.TemplateException;
    16 import freemarker.template.TemplateModel;
    17 import freemarker.template.TemplateScalarModel;
    18 
    19 @Service
    20 public class RoleDirectiveModel implements TemplateDirectiveModel{
    21 
    22     /**
    23      * env:环境变量
    24      * params:指令参数(存储所需的值,随便是什么Key-Value)
    25      * loopVars:循环变量
    26      * body:指令内容
    27      * 除params外,其他的都能是null
    28      */
    29     @Override
    30     public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
    31             throws TemplateException, IOException {
    32         System.out.println("=================");
    33         
    34         TemplateScalarModel user = (TemplateScalarModel) params.get("user");
    35         TemplateScalarModel role = (TemplateScalarModel) params.get("role");
    36         
    37         if("123456".equals(user.getAsString()) && "admin".equals(role.getAsString())) {
    38             loopVars[0] = TemplateBooleanModel.TRUE;
    39         }
    40         
    41         List<String> otherRights = new ArrayList<String>();
    42         otherRights.add("add");
    43         otherRights.add("update");
    44         otherRights.add("delete");
    45         loopVars[1] = new SimpleSequence(otherRights);
    46         
    47         // 输出
    48         body.render(env.getOut());
    49     }
    50 
    51 }

        b、注册自定义指令

     1 <bean id="freemarkerConfig"
     2       class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
     3     <property name="templateLoaderPath" value="" />
     4     <property name="freemarkerSettings">
     5         <props>
     6             <!-- 设置标签类型 两种:[] 和 <> , []这种标记解析要快些 -->
     7             <prop key="tag_syntax">auto_detect</prop>
     8             <!-- 检查模板更新时间间隔,默认5s -->
     9             <prop key="template_update_delay">1</prop>
    10             <prop key="default_encoding">UTF-8</prop>
    11             <prop key="url_escaping_charset">UTF-8</prop>
    12             <prop key="locale">zh-CN</prop>
    13             <!-- 时间格式化 -->
    14             <prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>
    15             <prop key="date_format">yyyy-MM-dd</prop>
    16             <prop key="time_format">HH:mm:ss</prop>
    17             <prop key="number_format">0.##########</prop>
    18             <!-- 去掉多余的空格 -->
    19             <prop key="whitespace_stripping">true</prop>
    20             <prop key="classic_compatible">true</prop>
    21             <prop key="template_exception_handler">ignore</prop>
    22         </props>
    23     </property>
    24     
    25     <!-- freemarker变量 -->
    26     <property name="freemarkerVariables">
    27         <map>
    28             <entry key="role" value-ref="roleDirectiveModel"></entry>
    29         </map>
    30     </property>
    31 </bean>

        c、在模板中使用自定义指令

     1 <!DOCTYPE html>
     2 <html>
     3 <head>
     4 <meta charset="UTF-8">
     5 <title>Insert title here</title>
     6 </head>
     7 <body>
     8     <h1>指令</h1>
     9     <h2>List常用指令</h2>
    10      <div>
    11          <#assign myList=[2,3,4,5,1,8,9,7] />
    12          <br />排序指令sort
    13          <ul>
    14              <#list myList?sort as item >
    15              <li>${item_index } - ${item }</li>
    16              </#list>
    17          </ul>
    18          <br />导至输出reverse
    19          <ul>
    20              <#list myList?sort?reverse as item >
    21              <li>${item_index } - ${item }</li>
    22              </#list>
    23          </ul>
    24          <br />大小
    25          <ul>
    26              <li>myList?size - ${myList?size }</li>
    27              <li>myList[3] - ${myList[3] }</li>
    28          </ul>
    29      </div>
    30     <h2>自定义指令</h2>
    31     
    32     <div>
    33          <@role user='123456' role='admin' ; result1, result2 >
    34          <br />例:用户123456 是否拥有admin角色,并返回admin权限
    35          <ul>
    36              <#if result1 >
    37              <li>我的角色是: amdin</li>
    38              </#if>
    39              我拥有的权限是:
    40              <#list result2 as item >
    41              <li>${item }</li>
    42              </#list>
    43          </ul>
    44          </@role>
    45      </div>
    46 </body>
    47 </html>

      6、FreeMarker内置函数

     1 <!DOCTYPE html>
     2 <html>
     3 <head>
     4 <meta charset="UTF-8">
     5 <title>Insert title here</title>
     6 </head>
     7 <body>
     8     <h1>内建函数</h1>
     9     <h2>1、字符串内建函数</h2>
    10      <div>
    11          <#assign myList=[2,3,4,5,1,8,9,7] />
    12          <br />split
    13          <ul>
    14              <#list 'a|b|c|d'?split('|') as item >
    15              <li>${item }</li>
    16              </#list>
    17          </ul>
    18          <br />字符串转日期
    19          <ul>
    20              <#assign var1 =  "01/03/2017"?date("MM/dd/yyyy") />
    21              <#assign var2 =  "15:05:30"?time("HH:mm:ss") />
    22              <#assign var3 =  "2019-07-22 03:05 PM"?datetime("yyyy-MM-dd HH:mm") />
    23              <li>${var1 }</li>
    24              <li>${var2 }</li>
    25              <li>${var3 }</li>
    26          </ul>
    27      </div>
    28      <h2>2、数字内建函数</h2>
    29      <div>
    30          <#assign numVar1=3.1415926 />
    31          <br />3.1415926
    32          <ul>
    33              <li>${numVar1?string("0.##") }</li>
    34              <li>${numVar1?round }</li>
    35          </ul>
    36      </div>
    37      <h2>3、List内建函数</h2>
    38      <div>
    39          <#assign myList1=[2,3,4,5,1,8,6,9,7] />
    40          <br />chunk
    41          <ul>
    42              <li>${myList1?chunk(3)?size }</li>
    43              <#list myList1?chunk(3)?last as item >
    44              <li>${item }</li>
    45              </#list>
    46          </ul>
    47      </div>
    48      <h2>4、其他内建函数</h2>
    49      <div>
    50          <#assign sVar="hello" />
    51          <br />hello
    52          <ul>
    53              <li>${sVar?is_number?string('yes', 'no') }</li>
    54              <li>${sVar?has_content?string('yes', 'no') }</li>
    55              <li>${"1" + "2" ? eval }</li>
    56              <li>${vDefault!"sss" }</li>
    57          </ul>
    58      </div>
    59     
    60 </body>
    61 </html>

      7、macro宏指令

     1 <!DOCTYPE html>
     2 <html>
     3 <head>
     4 <meta charset="UTF-8">
     5 <title>Insert title here</title>
     6 </head>
     7 <body>
     8     <h1>模板中使用macro指令定义</h1>
     9     <h2>1、macro:宏指令</h2>
    10      <div>
    11          <br />无参数的macro
    12          <ul>
    13              <#macro test>
    14              <li>我是无参的macro</li>
    15              </#macro>
    16              <@test />
    17          </ul>
    18          <br />有参数的macro
    19          <ul>
    20              <#macro test param1 param2>
    21              <li>我是有参的macro param1 = ${param1}, param2 = ${param2}</li>
    22              </#macro>
    23              <@test param1="java" param2="python" />
    24          </ul>
    25          <br />有默认值参数的macro
    26          <ul>
    27              <#macro test param1 param2="def">
    28              <li>我是有默认值参数的macro param1 = ${param1}, param2 = ${param2}</li>
    29              </#macro>
    30              <@test param1="java"  />
    31          </ul>
    32          <br />有多个参数的macro
    33          <ul>
    34              <#macro test param1 param2="def" paramExt... >
    35              <li>有多个参数的macro param1 = ${param1}, param2 = ${param2}</li>
    36              <li>${paramExt["param3"]} </li>
    37              </#macro>
    38              <@test param1="java" param2="python" param3="html"/>
    39          </ul>
    40      </div>
    41      <h2>2、nested</h2>
    42      <div>
    43          <br />嵌套
    44          
    45          <ul>
    46              <#macro test  param1="java">
    47              <li>${param1 }</li>我是无参的macro<br />
    48              <#nested param1, "我的nested 参数">
    49              </#macro>
    50              <@test param1="java1"; loopVar1, loopVar2>
    51                  <font color="red">hello ${loopVar1}, ${loopVar2}</font>
    52              </@test>
    53              <@test param1="java2"; loopVar1, loopVar2>
    54                  hello ${loopVar1}, ${loopVar2}
    55              </@test>
    56          </ul>
    57      </div>
    58      <h2>2、函数</h2>
    59      <div>
    60          <br />函数调用
    61          
    62          <ul>
    63              <#function doAdd  param1 param2>
    64                  <#return param1+param2 > 
    65              </#function>
    66              <li>${doAdd(20, 30) }</li>
    67          </ul>
    68      </div>
    69     
    70 </body>
    71 </html> 
  • 相关阅读:
    ios in-house 公布整个过程(startssl认证)
    各种图的创建以及广度,深度优先遍历(临接矩阵存储)
    SWTBOK測试实践系列(1) -- 測试在项眼下期的评审投入划算吗?
    欢天喜地迎国庆,国产开源编程语言 RPP 1.87 公布!
    正确地在QML应用中使用fontsize
    iOS 9音频应用播放音频之第一个ios9音频实例
    iOS 9音频应用播放音频之ios9音频基本功能
    iOS 9音频应用开发基础教程
    MAC OS 10.11.1虚拟机免费下载已安装Xcode7图片后有下载地址
    检验Xcode是否被改动过的简单方法,不妨试试!!!
  • 原文地址:https://www.cnblogs.com/h--d/p/11233168.html
Copyright © 2020-2023  润新知