Last active
September 30, 2018 02:35
-
-
Save guozi/d20a94869da096762571163cad8f1f78 to your computer and use it in GitHub Desktop.
FreeMarkerUtil
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import freemarker.template.Configuration; | |
import freemarker.template.Template; | |
import freemarker.template.TemplateException; | |
import lombok.extern.slf4j.Slf4j; | |
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils; | |
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer; | |
import java.io.IOException; | |
import java.io.StringReader; | |
import java.io.StringWriter; | |
import java.util.Map; | |
/** | |
* Created by guozi on 2018/5/16. | |
*/ | |
@Slf4j | |
public class FreeMarkerUtil { | |
/** | |
* 解析字符串模板 | |
* | |
* @param template 字符串模板信息 | |
* @param model 替换参数信息 | |
* @return 替换后的模板 | |
* @throws IOException | |
* @throws TemplateException | |
*/ | |
public static String process(String template, Map model) throws IOException, TemplateException { | |
Configuration configuration = null; | |
FreeMarkerConfigurer freemarkerconfigurer = SpringUtil.getBean("freeMarkerConfigurer", FreeMarkerConfigurer.class); | |
if (freemarkerconfigurer != null) { | |
configuration = freemarkerconfigurer.getConfiguration(); | |
} | |
return process(template, model, configuration); | |
} | |
public static String process(String templateContent, Map model, Configuration configuration) throws IOException, TemplateException { | |
if (templateContent == null) { | |
return null; | |
} | |
if (configuration == null) { | |
configuration = new Configuration(Configuration.VERSION_2_3_26); | |
} | |
StringWriter stringwriter = new StringWriter(); | |
try { | |
(new Template("templateContent", new StringReader(templateContent), configuration)).process(model, stringwriter); | |
} catch (TemplateException | IOException ex) { | |
log.error("FTL 解析出错,模板:{},参数:{}", templateContent, model, ex); | |
throw ex; | |
} | |
return stringwriter.toString(); | |
} | |
public static String processTemplate(String templateName, Map model, Configuration configuration) throws IOException, TemplateException { | |
if (templateName == null) { | |
return null; | |
} | |
if (configuration == null) { | |
configuration = new Configuration(Configuration.VERSION_2_3_26); | |
} | |
try { | |
Template template = configuration.getTemplate(templateName); | |
return FreeMarkerTemplateUtils.processTemplateIntoString(template, model); | |
} catch (TemplateException | IOException ex) { | |
log.error("FTL 解析出错,模板:{},参数:{}", templateName, model, ex); | |
throw ex; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment