FreeMarker 基本知识

什么是 FreeMarker?

freeMarker一种基于模板和要改变的数据, 并用来生成输出文本(HTML网页,电子邮件,配置文件,源代码等)的通用工具。 它不是面向最终用户的,而是一个Java类库,FreeMarker最初的设计,是被用来在MVC模式的Web开发框架中生成HTML页面、也可以生成代码如:DTO、Service、Model、grovvy脚本

Figure
example

使用场景

  1. html 模板生成
  2. xml 报文生成,如银行类交互报文
  3. json 报文生成,请求报文配置化平台
  4. drools 规则引擎脚本使用模板

标量

  • 字符串: ‘字符串’ 或 “字符串”
  • 数值 : 100
  • 布尔值:<#if loggedIn >...</#if> 或者 <#if price == 0>...</#if>
  • 日期:

容器(是包含变量)

  • 哈希表(map)
  • 序列(数组)
  • 集合(list):从模板设计者角度来看,集合是有限制的序列。不能获取集合的大小, 也不能通过索引取出集合中的子变量,但是它们仍然可以通过 list 来遍历

子程序

  • 函数、方法

总体结构

  • 实际上用程序语言编写的程序就是模板。 FTL (代表FreeMarker模板语言)。 这是为编写模板设计的非常简单的编程语言,FTL包含如下:
    • 文本
    • 插值
    • FTL标签
    • 注释

指令

  • 开始标签<#指令 参数>
  • 结束标签</#指令>
    • <#if x == 1> x is 1 </#if>
    • <#if x == 1> x is 1 <#elseif x == 2> x is 2 <#elseif x == 3> x is 3 </#if>
  • 常用指令if :
    • ${user.name},异常
    • ${user.name!},显示空白
    • ${user.name!’vakin’},若user.name不为空则显示本身的值,否则显示vakin
    • ${user.name?default(‘vakin’)} ,同上
    • ${user.name???string(user.name,’vakin’)},同上
    • userName?has_content,not empty
  • list : <#list users as user> <p>${user} </#list> use是每次循环的变量
    • <#items>:通常搭配list使用,循环中出现有些信息只出现一次,。需要使用items
    • <#sep>, </#sep>: 和joiner 异曲同工,最后一次不出现
    • <#break>: list 循环中可以跳出循环
  • switch:<#switch animal.size>
    <#case “small”> This will be processed if it is small <#break>
    <#default> This will be processed if it is neither
    </#switch>

demo

Configuration cfg = new Configuration();
        StringTemplateLoader stringLoader = new StringTemplateLoader();
        stringLoader.putTemplate("myTemplate", "{\"merchantId\":\"${merchantId}\",\"countryCode\":\"**\",\"paymentMethod\":\"${paymentMethod}\",\"currency\":\"${currency}\",\"channelId\":\"${channelId}\",\"map\":{\"test\":\"${map.mapKey}\"}}");
        cfg.setTemplateLoader(stringLoader);
        Template temp = cfg.getTemplate("myTemplate","utf-8");
        /* 创建数据模型 */
        Map root = new HashMap();
        root.put("merchantId"  ,"merchantId"  );
        root.put("paymentMethod" ,"paymentMethod"  );
        root.put("currency"  ,"currency"  );
        root.put("channelId"  ,"channelId"  );
        root.put("map"  ,ImmutableMap.of("mapKey","mapValue") );

        Writer out = new StringWriter(2048);
        temp.process(root, out);
        System.out.println(out.toString());
        out.flush();

freemarker在线编辑:https://www.renfei.net/kitbox/freemarkerTest