`

freemark 自定义标签 总结

阅读更多

参考:

http://grails.org/doc/latest/ref/Tags/select.html

http://freemarker.sourceforge.net/

 

调用:

<@d_select id="type_4" optionKey="position" optionValue="id" list=adSpaceBoList callBack="test();" value="4f0eabc9073c1f0de52b25d2" ></@d_select> 指定list对象名:list=adSpaceBoList;选项key对应集合中的属性:optionKey="position";选项value对应集合中的属性:optionValue="id";

 

实现类:

implements TemplateDirectiveModel

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

// id
        String id = MapUtils.getString(params, "id", "selectId");

// multiple

boolean multiple = Boolean.valueOf(MapUtils.getString(params, "multiple"));

// onEventName:默认有callback时为onChange
        String onEventName = MapUtils.getString(params, "onEventName","onChange");

 

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

//list
        Object temp = params.get("list");
        if(temp instanceof SimpleSequence){
            SimpleSequence lists = (SimpleSequence) params.get("list");

            templateContext.put("list",lists.toList());
        }
       
        //strList
        String strList = MapUtils.getString(params, "strList");// strList : 文字:1,图片:2
        if(StringUtils.isNotBlank(strList)){
            if(StringUtils.isNotBlank(strList)){
                templateContext.put("strList", Arrays.asList(strList.split(",")));
            }
        }
       
        //map
        SimpleHash map=(SimpleHash)params.get("map");
        if(null!=map){
            templateContext.put("map",map.toMap());
        }

 

templateContext.put("id", id);

//.....

 

        Template template = env.getConfiguration().getTemplate("/ftl/select.ftl");
        template.process(templateContext, env.getOut());

}

 

页面:

eval:把字符串当做ftl代码处理;处理后对象的值要以string的length来判断,如果直接用??,则对象为空 ;

 

<#list list as obj>
        <#if obj??>
            <#assign keys = ('obj.'+ optionKey) >
            <#assign values = ('obj.'+ optionValue) >
            <#if ((values?eval)?length gt 0 && (keys?eval)?length gt 0) >
                <option value="${values?eval}" <#if ((value??)&& value == values?eval) >selected</#if>>${keys?eval!''}</option>
            </#if>
        </#if>
    </#list>

 

最后,还要在项目里注册自定义的标签;

注册:
sothis.properties
sothis.freemarker.directive.d_select.class=com.fangjia.bkoff.util.SelectDirective

 

底层(部分):

private SothisConfig config;

 

String configLocation = filterConfig.getInitParameter("configLocation");
                if (null == configLocation) {
                    configLocation = "sothis.properties";
                }
                config = SothisConfig.initConfig(configLocation);

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics