Skip to content

2.3版本 freemarker自定义标签介绍

朋也 edited this page Apr 14, 2017 · 1 revision

积分榜,权限用的都是自定义标签做的 拿积分榜的用法来说明 创建 ScoresDirective 集成 TemplateDirectiveModel 实现里面的方法 excute

public class ScoresDirective implements TemplateDirectiveModel {

    @Override
    public void execute(Environment environment, Map map, TemplateModel[] templateModels,
                        TemplateDirectiveBody templateDirectiveBody)
            throws TemplateException, IOException {
        List<User> scores = new ArrayList<User>();
        if(map.containsKey("limit") && map.get("limit") != null) {
            scores = User.me.scores(10);
        }
        DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_23);
        environment.setVariable("list", builder.build().wrap(scores));
        templateDirectiveBody.render(environment.getOut());
    }
}

获取标签中属性的值都是从map参数里拿的 输出对象通过environment对象输出

标签名字是什么,怎么指定呢? 看看 PyTag.java 就知道了

public class PyTag extends SimpleHash {

    public PyTag() {
        put("hasPermission", new PermissionDirective());
        put("scores", new ScoresDirective());
    }
}

最后就是配置在JFinalConfig里了

FreeMarkerRender.getConfiguration().setSharedVariable("py", new PyTag());

使用方法:

<@py.scores limit=10>
    <#list list as u>
        <tr>
            <td><a href="/user/${u.nickname!}">${u.nickname!}</a></td>
            <td <#if hidden == "true">class="hidden"</#if>><a href="${u.url!}">${u.url!}</a></td>
            <td <#if hidden == "true">class="hidden"</#if>>${u.description!}</td>
            <td>${u.score!}</td>
        </tr>
    </#list>
</@py.scores>