优化代码生成器模板引擎

v1.4.1
hiparker 4 years ago
parent c2b047b0e5
commit 5c91e96d79

@ -1,49 +1,57 @@
package org.opsli.core.creater.utils;
import cn.hutool.core.io.IoUtil;
import com.google.common.collect.Maps;
import com.jfinal.kit.Kv;
import com.jfinal.template.Engine;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ClassPathResource;
import java.io.File;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;
/***
* jfinal
* @author dufuzhong
* Enjoy
* @author Parker
*/
@Slf4j
public final class EnjoyUtil {
private static final String BASE_PATH = "/tpl";
/** 模板文件Map */
private static final Map<String, String> TEMPLATE_FILE_MAP = Maps.newConcurrentMap();
/**
*
* @param templateFileName
* @param kv
* @return
* @return String
*/
public static String render(String templateFileName, Kv kv) {
String str = "";
ClassPathResource resource = new ClassPathResource(BASE_PATH + templateFileName);
try (InputStream inputStream = resource.getInputStream()){
String readTpl = IoUtil.read(inputStream, StandardCharsets.UTF_8);
str = Engine.use()
// 开启预热模式
.setDevMode(true)
.getTemplateByString(readTpl)
.renderToString(kv);
} catch (Exception e) {
log.error("load config file {} error", templateFileName, e);
public static String render(final String templateFileName, Kv kv) {
// 模板缓存 减少每次更新
String templateFile = TEMPLATE_FILE_MAP.get(templateFileName);
if(StringUtils.isEmpty(templateFile)){
// 如果为空 则IO 读取原始文件
ClassPathResource resource = new ClassPathResource(BASE_PATH + templateFileName);
try (InputStream inputStream = resource.getInputStream()){
templateFile = IoUtil.read(inputStream, StandardCharsets.UTF_8);
TEMPLATE_FILE_MAP.put(templateFileName, templateFile);
} catch (Exception e) {
log.error("load file {} error", templateFileName, e);
}
}
return str;
}
return Engine.use()
// 开启预热模式
.setDevMode(true)
.getTemplateByString(templateFile)
.renderToString(kv);
}
private EnjoyUtil(){}

Loading…
Cancel
Save