首页 > 编程语言 > 详细

SpringBoot整合freemarker中自定义标签获取字典表的数据

时间:2018-04-09 18:32:18      阅读:302      评论:0      收藏:0      [点我收藏+]
因为在前端要根据字典表中的数据去将1、2这些值转换成对应的文字解释
1.首先要创建一个类去实现 TemplateDirectiveModel 类
@Component
public class DictDirective implements TemplateDirectiveModel {

    @Override
    public void execute(Environment environment, Map map, TemplateModel[] templateModels, TemplateDirectiveBody templateDirectiveBody) throws TemplateException, IOException {
        DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_25);
        if(map.containsKey("type") && map.get("type") != null){
            String type = map.get("type").toString();
            List<Dict> dictList = DictUtils.getDictList(type);
            if(map.containsKey("value") && map.get("value") != null){
                String value = map.get("value").toString();
                Dict dict = null;
                for (Dict dict1 : dictList) {
                    if(value.equals(dict1.getValue().toString())){
                        dict = dict1;
                    }
                }
                environment.setVariable("dict", builder.build().wrap(dict));
            }else{
                environment.setVariable("dictList", builder.build().wrap(dictList));
            }
        }
        if(templateDirectiveBody!=null){
            templateDirectiveBody.render(environment.getOut());
        }
    }
} 

 

2.创建一个配置类
@Component
public class FreemarkerConfig {
    @Autowired
    private Configuration configuration;
    @Autowired
    private DictDirective dictDirective;

    @PostConstruct
    public void setSharedVariable() throws TemplateModelException {
        configuration.setSharedVariable("dict_tag", dictDirective);
    }
}
然后就可以在页面上去调用了
<@dict_tag type="news_source" value="${news.source}">
                        ${dict.label}
                    </@dict_tag>

技术分享图片

前端可以任意传递参数,像type、value这样的,所有传递的参数都会被存到map里面,后台直接去取就可以了

SpringBoot整合freemarker中自定义标签获取字典表的数据

原文:https://www.cnblogs.com/liangshandada/p/8761463.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!