Freemarker自定义函数的使用

1. 编写函数

 

 

 

public class FtlCheckPermissionMethod implements TemplateMethodModel {

	@SuppressWarnings("rawtypes")
	@Override
	public Object exec(List args) throws TemplateModelException {
		String permissionsStr = args.get(0).toString();
		String permission = args.get(1).toString();
		String[] permissionsArray = permissionsStr.split(SessionUtil.PERMISSION_SPLIT);
		for (String per : permissionsArray) {
			if (permission.equals(per)) {
				return true;
			}
		}

		return false;
	}
}

 

 

2.注册与使用

   有两种方式:

  (1).在模板文件中注册,在模板中使用

 

 

<#assign checkPermission= "com.beyondsoft.common.util.FtlCheckPermissionMethod"?new()>
<#macro leftMenu menu>
	
    <#if checkPermission(permissions,"VW_ACCOUNT")>
  • class="on">Account Management
  • <#if checkPermission(permissions,"VW_ROLE_MANAGEMENT")>
  • class="on">Role Management
  • <#if checkPermission(permissions,"VW_RESET_PASSWORD")>
  • class="on">Reset Password
  • <#if checkPermission(permissions,"VW_REVIEW_HISTORY")>
  • class="on">Review History

 

 

 (2).处理模板文件时注册
    关键代码:

Map root=new HashMap();          
root.put("getSysdate", new StringLengthMethod());
Configuration config=new Configuration();                         
File file=new File(templatePath); //并加载模板文件              
config.setDirectoryForTemplateLoading(file);  //设置包装器,并将对象包装为数据模型              
config.setObjectWrapper(new DefaultObjectWrapper()); //获取模板,并设置编码方式,这个编码必须要与页面中的编码格式一致              
Template template=config.getTemplate(templateName,templateEncoding); //合并数据模型与模板                            
template.process(root, out);

 

你可能感兴趣的:(freemarker)