【未接迷】Freemarker自定义字符串截取标签

通过截取字符串,保证英文和中文长度一致

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.Iterator;
import java.util.Map;

import junit.framework.Assert;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateNumberModel;
import freemarker.template.TemplateScalarModel;

/**
 * 截取字符串
 * @author wy
 *
 */
public class CutTemplateDirectiveModel implements TemplateDirectiveModel{
    /**
     * 截取字符串
     */
    private static final String TEXT ="text";
    
    /**
     * 截取长度,默认为10
     */
    private static final String LENGTH ="length";
    
    /**
     * 截取后+的字符串...
     */
    private static final String EXT = "ext";    
    
    
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public void execute(Environment env, Map params, TemplateModel[] templateModels, TemplateDirectiveBody body) throws TemplateException, IOException {
        Iterator<Map.Entry> paramIter = params.entrySet().iterator();
        String text = null;
        String ext="";
        int length=10;
        while (paramIter.hasNext()) {
            Map.Entry ent = paramIter.next();
            String paramName = (String) ent.getKey();
            TemplateModel paramValue = (TemplateModel) ent.getValue();
            if (paramName.equals(TEXT)) {
                if (paramValue instanceof TemplateScalarModel) {
                    text = ((TemplateScalarModel) paramValue).getAsString();
                }
                else{
                    throw new RuntimeException("Value not String");
                }
            }                
            if (paramName.equals(LENGTH)) {
                if (paramValue instanceof TemplateNumberModel) {
                    length = ((TemplateNumberModel) paramValue).getAsNumber().intValue();
                }
                else{
                    throw new RuntimeException("Length not int");
                }
            }
            if (paramName.equals(EXT)) {
                if (paramValue instanceof TemplateScalarModel) {
                    ext = ((TemplateScalarModel) paramValue).getAsString();
                }
                else{
                    throw new RuntimeException("Value not String");
                }
            }
            
        }
        Assert.assertNotNull(text);            
        if(body!=null){
            Writer out = env.getOut();
            out.append(subString(text, length, ext));
            body.render(out);
        }
        else{
            Writer out = env.getOut();
            out.append(subString(text, length, ext));
        }

    }
    private static String subString(String text, int length, String ext) {  
        int textLength = text.length();  
        int byteLength = 0;  
        StringBuffer returnStr =  new StringBuffer();  
        for(int i = 0; i<textLength && byteLength < length*2; i++){  
            String str_i = text.substring(i, i+1);   
            if(str_i.getBytes().length == 1){//英文  
                byteLength++;  
            }else{//中文  
                byteLength += 2 ;  
            }  
            returnStr.append(str_i);  
        }  
        try {  
            if(byteLength<text.getBytes("GBK").length){//getBytes("GBK")每个汉字长2,getBytes("UTF-8")每个汉字长度为3  
                returnStr.append(ext);  
            }  
        } catch (UnsupportedEncodingException e) {  
            e.printStackTrace();  
        }  
        return returnStr.toString();  
    }  
}


然后在FTL模板头部写入

<#assign cut="com.cms.freemarker.CutTemplateDirectiveModel"?new()>

使用方法:<@cut text="CXCCCCCCC中文aaa" length=12  ext='...'/>

具体信息请查看:未解谜


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值