欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringMVC Freemarker 自定义标签

程序员文章站 2022-06-08 23:46:32
...

1:实现 freemarker.template.TemplateMethodModelEx 接口对于 freemarker-2.3.20版本, 更早版本实现freemarker.template.TemplateMethodModel 接口

且加入Spring管理,代码如下:

package com.sqtoon.orderserv.web.commons.freemarker.tag;

import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Component;

import freemarker.template.TemplateMethodModelEx;
import freemarker.template.TemplateModelException;

@Component("dictItemTag")
public class DictItemTag implements TemplateMethodModelEx { // TemplateMethodModel

	@SuppressWarnings("rawtypes")
	@Override
	public Object exec(List arguments) throws TemplateModelException {
		StringBuilder ret = new StringBuilder("DictItemTag");
		if (CollectionUtils.isNotEmpty(arguments)) {
			for (Object obj : arguments) {
				ret.append("-").append(obj);
			}
		}
		return ret.toString();
	}

}

 

2: 配置Spring 中的org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer :

<!-- FreeMarker配置 -->
 	<bean id="freeMarkerConfigurer" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
		<property name="templateLoaderPath" value="/WEB-INF" />
		<property name="defaultEncoding" value="UTF-8" />
		<property name="freemarkerVariables">
			<map>
				<entry key="dictItemTag" value-ref="dictItemTag"/>
			</map>
		</property>
		<property name="freemarkerSettings">
			<props>
				<prop key="tag_syntax">auto_detect</prop>
				<prop key="template_update_delay">0</prop>
				<prop key="defaultEncoding">UTF-8</prop>
				<prop key="output_encoding">UTF-8</prop>  
				<prop key="url_escaping_charset">UTF-8</prop>
				<prop key="locale">zh_CN</prop>
				<prop key="boolean_format">true,false</prop>
				<prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>
				<prop key="date_format">yyyy-MM-dd</prop>
				<prop key="time_format">HH:mm:ss</prop>
				<prop key="number_format">0.######</prop>
				<prop key="whitespace_stripping">true</prop>
				<prop key="classic_compatible">true</prop>
				<!-- <prop key="auto_import">/ftl/spring.ftl as s</prop> 
				<prop key="template_exception_handler">ignore</prop> -->
			</props>
		</property>
	</bean>

 3:页面使用:

${dictItemTag('one!','two!!','three!!!','go!!!!')}

 

页面输出结果为:

DictItemTag-one!-two!!-three!!!-go!!!!

4:完毕!