首页 > 代码库 > Freemarker自定义标签

Freemarker自定义标签

一、 用macro实现自定义指令,例如:

自定义指令可以使用macro指令来定义。
     <#macro greet person>
            <font size="+2">Hello ${person}!</font>
     </#macro>
     macro指令自身不打印任何内容,它只是用来创建宏变量,所以就会有一个名为greet的变量。
使用这个宏:
    <@greet person="Fred"/>
会打印出:
    <font size="+2">Hello Fred!</font>

二、用java代码标签实现自定义指令:

可以使用TemplateDirectiveModel接口在Java代码中实现自定义指令。
简单示例如下:

1、实现TemplateDirectiveModel接口。
            public class UpperDirective implements TemplateDirectiveModel {
                  public void execute(Environment env,
                           Map params, TemplateModel[] loopVars,
                           TemplateDirectiveBody body)
                           throws TemplateException, IOException {
                            if (!params.isEmpty()) {
                             throw new TemplateModelException(
                               "parameters 此处没有值!");
                            }
                           if (loopVars.length != 0) {
                           throw new TemplateModelException(
                          " variables 此处没有值!");
                          }
                         if (body != null) {
                         //执行nested body  与FTL中 <#nested> 类似。
                     body.render(new UpperCaseFilterWriter(env.getOut()));
                         } else {
                        throw new RuntimeException("missing body");
                         }
                    }
           private static class UpperCaseFilterWriter extends Writer {
           private final Writer out;
           UpperCaseFilterWriter (Writer out) {
            this.out = out;
        }        
        public void write(char[] cbuf, int off, int len)
            throws IOException {
            char[] transformedCbuf = new char[len];
                for (int i = 0; i < len; i++) {
                               transformedCbuf[i] = Character.toUpperCase(cbuf[i + off]);
                }
                    out.write(transformedCbuf);
            }
        public void flush() throws IOException {
                out.flush();
            }
                public void close() throws IOException {
                out.close();
                }
           }
       }

     说明:<#nested>指令执行位于开始和结束标记指令之间的模板代码段。


2、注入FreeMarkerConfigurer的freemarkerVariables中。
     例如:在applicationContext.xml
    <entry key="upper" value-ref="upper"/>
    <bean id="upper" class="com.example.UpperDirective" />

   说明:
   FreeMarkerConfigurer. 、setFreemarkerVariables(Map<String,Object> variables)
   底层调用了FreeMarker的Configuration.setAllSharedVariables()方法。
   因为更好的实践是将常用的指令作为共享变量放到Configuration中。

3、调用自定义指令:

     [@upper]
            bar
            [#list ["red", "green", "blue"] as color]
                  ${color}
            [/#list]
            baaz
     [/@upper]

4、显示输出结果:
      BAR RED GREEN BLUE BAAZ

Freemarker自定义标签