freemarker如何编写自定义标签

编写自定义标签需要实现 freemarker.template.TemplateDirectiveModel 接口
demo如下

freemarker模板   freemarker自定义标签.ftl
<#assign x = 1>
<@repeat count=4>
Test ${x}
<#assign x = x + 1>
</@repeat>

<@repeat count=3; cnt>
${cnt}. Test
</@repeat>
TemplateDirectiveModel  接口的实现类

package com.yydb.lp.freemarker.customlabel;

import java.io.IOException;
import java.io.Writer;
import java.util.Map;

import freemarker.core.Environment;
import freemarker.template.SimpleNumber;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;
import freemarker.template.TemplateNumberModel;

public class RepeatDirective implements TemplateDirectiveModel {

    /**
     * @param environment
     * @param map
     *            <@repeat count=3;
     *            cnt>其中count=3就以键值对的形式存在map中,只是3不是java类型,而是TemplateModel类型
     *            (整数:TemplateNumberModel
     *            ,字符串:TemplateScalarModel,boolean:TemplateBooleanModel 等),
     *            所以利用map.getValue(......)返回的是一个TemplateModel类型的数据,需转换成int类型数据。
     * @param atemplatemodel
     *            变量,如cnt,atemplatemodel是一个TemplateModel类型的数组,我们可以在程序中给它赋值
     * @param templatedirectivebody
     */
    @Override
    public void execute(Environment environment, Map map, TemplateModel atemplatemodel[], TemplateDirectiveBody templatedirectivebody) {
        Writer out = null;
        try {
            if (templatedirectivebody == null) {// 自定义标签必须有内容,即自定义 开始标签与结束标签之间必须有 内容
                throw new TemplateModelException("null body");
            } else {
                out = environment.getOut();
                // TemplateNumberModel 数字类型, TemplateScalarModel 字符串类型,
                // TemplateBooleanModel boolean类型
                TemplateNumberModel numberModel = (TemplateNumberModel) map.get("count");
                int count = numberModel.getAsNumber().intValue();
                for (int i = 0; i < count; i++) {
                    if (atemplatemodel.length > 0) {
                        atemplatemodel[0] = new SimpleNumber(i + 1);
                    }
                    templatedirectivebody.render(out);
                }
            }
        } catch (TemplateModelException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(out != null) {
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}

测试代码

import freemarker.cache.FileTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public static void  main(String[] aegs) throws IOException, TemplateException {
        Configuration configuration = new Configuration();
        configuration.clearTemplateCache();

        configuration.setTemplateLoader(new FileTemplateLoader(new File("D:/")));
        Template template = configuration.getTemplate("/freemarker自定义标签.ftl",Locale.CHINA,"UTF-8");

        Map<String,Object> rootMap = new HashMap<String,Object>();

        //以下两行代码功能是一样的,这里我们使用第二行代码
//      configuration.setSharedVariable("repeat", new RepeatDirective());
        rootMap.put("repeat", new RepeatDirective());


        StringWriter sw = new StringWriter();
        template.process(rootMap, sw);
        System.out.println(sw.toString());
    }
自定义一个名为 ListDirective 的 FreeMarker 指令,你需要遵循以下步骤: 1. 创建一个 Java 类来实现指令。这个类应该继承 `freemarker.template.TemplateDirectiveModel` 接口,并且需要实现 `execute()` 方法,该方法会被 FreeMarker 引擎调用来处理指令。 ```java import java.util.Map; import javax.servlet.jsp.JspException; import javax.servlet.jsp.PageContext; import freemarker.core.Environment; import freemarker.template.*; public class ListDirective implements TemplateDirectiveModel { public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, java.io.IOException { // 在这里编写逻辑来处理指令 // ... } } ``` 2. 在 `execute()` 方法中编写处理逻辑。在这里,你需要解析和验证指令参数,并使用 `TemplateModel` 对象来获取指令所在的模板环境和输出流。你也需要创建一个 `SimpleScalar` 对象来包装列表数据,并将其放入模板环境中。 ```java public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, java.io.IOException { // 解析和验证指令参数 String listName = DirectiveUtils.getRequiredParam(params, "name"); Object listData = DirectiveUtils.getRequiredParam(params, "data"); // 获取模板环境和输出流 Writer out = env.getOut(); PageContext pageContext = (PageContext) env.getCustomAttribute("PageContext"); if (pageContext == null) { throw new JspException("PageContext not found"); } // 创建 SimpleScalar 对象来包装列表数据 SimpleScalar listModel = new SimpleScalar(listData.toString()); // 将 SimpleScalar 对象放入模板环境中 env.setVariable(listName, listModel); // 处理指令内容 if (body != null) { body.render(out); } } ``` 3. 将自定义指令注册到 FreeMarker 引擎中。你可以使用 `Configuration` 对象的 `setSharedVariable()` 方法将指令实例添加到引擎中。 ```java import freemarker.template.Configuration; Configuration cfg = new Configuration(Configuration.VERSION_2_3_30); cfg.setSharedVariable("list", new ListDirective()); ``` 现在,你就可以在模板中使用自定义指令了: ``` <@list name="myList" data=[1, 2, 3]> <#list myList as item> ${item} </#list> </@list> ``` 这将输出: ``` 1 2 3 ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值