Freemarker自定义标签

springboot 环境

查询字典标签

@Component

public class DicTag implements TemplateDirectiveModel {

 

    @Autowired

    private IDicService dicService;

 

    @Override

    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {

        //字典类型

        String TYPE = "type";

        //字典父id

        String PID = "pid";

        String type;

        Integer pid;

        if(params.containsKey(TYPE)){

            type = params.get(TYPE).toString();

        }else{

            throw new KrtException("字典类型不能为空");

        }

        if(params.containsKey(PID)){

            pid = Integer.valueOf(params.get(PID).toString());

        }else{

            pid = SysConstant.DEFAULT_PID;

        }

        List<Dic> dicList = dicService.selectByTypeAndPid(type,pid);

        loopVars[0] = new SimpleSequence(dicList,env.getObjectWrapper());

        body.render(env.getOut());

    }

}


实现TemplateDirectiveModel 接口

重写execute方法参数说明  这里可以做数据库查询 ,或者渲染模板数据输出

env 当编写复杂的标签时需要使用 一般用不到

params标签输入参数
loopVars 标签输出参数
body 标签体
SimpleSequence 是freemarker的数据类型  freemarker不能直接使用java的数据类型

以上代码编写完成后 设置全局变量时标签生效

@Component

public class FreemarkerConfig implements InitializingBean {

 

    @Autowired

    private Configuration configuration;

 

    @Autowired

    private DicTag dicTag;

 

    @Override

    public void afterPropertiesSet() throws Exception {

        // shiro标签

        configuration.setSharedVariable("shiro"new ShiroTags());

        //标签名与标签类

        configuration.setSharedVariable("dic", dicTag);

    }

 

}

模板上使用标签

<@dic type="region_type";typeList>

    <#list typeList as type>

        <option value="${type.code}">${type.name}</option>

    </#list>

</@dic>

type 是输入参数 字典type  多个参数中间空格  多个输出参数 用“,”隔开   typeList 就是字典数据

官方文档http://freemarker.foofun.cn/pgui_datamodel_directive.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值