FreemarkerUtils


import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

/**
 * @author lengchunyang
 * @date 2020/6/17 11:02
 */
@Component
public class FreemarkerUtils {

    /**
     *
     * @param filePath 模板文件名称
     * @param freemarkerContext 模板内容
     * @return
     */
    public String loadFtlHtml(String filePath,Map freemarkerContext) throws IOException {
        if(filePath.startsWith("/")){
            filePath = filePath.substring(1);
        }
        int index = filePath.lastIndexOf("/");
        String absolutePath = filePath.substring(0, index);
        ClassPathResource classPathResource = new ClassPathResource(absolutePath);

        File templateDir = classPathResource.getFile();
        String fileName = filePath.substring(index+1);

        Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);
        try {
            cfg.setDirectoryForTemplateLoading(templateDir);
            cfg.setDefaultEncoding("UTF-8");
            //.RETHROW
            cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
            cfg.setClassicCompatible(true);
            Template temp = cfg.getTemplate(fileName);

            StringWriter stringWriter = new StringWriter();
            temp.process(freemarkerContext, stringWriter);

            return stringWriter.toString();
        } catch (IOException | TemplateException e) {
            e.printStackTrace();
            throw new RuntimeException("load fail file");
        }
    }
}


/**
* 示例
*/
public static void main(String args[]){
 		Map context = new HashMap<>();
        context.put("testTitle","这是标题");
        context.put("testContent","这是标题");

        String tempHtml = freemarkerUtils.loadFtlHtml("/freemarker/templates/Temp.ftl", context);
}

你可能感兴趣的:(freemarkrer)