Freemarker靜態化時渲染自定義標籤

需要渲染自定義標籤

設置標籤類型([]、<>),[]這種標記解析要快些 默認是自動檢測語法  
//  自動 AUTO_DETECT_TAG_SYNTAX  
//  尖括號 ANGLE_BRACKET_TAG_SYNTAX  
//  方括號 SQUARE_BRACKET_TAG_SYNTAX

屬性設置

Configuration cfg = new Configuration();
cfg.setTagSyntax(Configuration.AUTO_DETECT_TAG_SYNTAX);

加載 獲取實現TemplateDirectiveModel的bean

第一種:

//獲取servletContext
WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext(); 
ServletContext servletContext = webApplicationContext.getServletContext();
ApplicationContext applicationContext = SpringContextUtil.getApplicationContext();
// 取出上下文
Map<String, TemplateDirectiveModel> beans = applicationContext.getBeansOfType(TemplateDirectiveModel.class);
// 獲取實現TemplateDirectiveModel的bean
for (String key : beans.keySet()) {
<span style="white-space:pre">	</span>Object obj = beans.get(key);
<span style="white-space:pre">	</span>if (obj != null && obj instanceof TemplateDirectiveModel) {
<span style="white-space:pre">		</span>freemarker_cfg.setSharedVariable(key, obj);
<span style="white-space:pre">	</span>}
}


第二種:

//加載實現TemplateDirectiveModel的自定義標籤Bean對象
Configuration cfg = new Configuration();
FreeMarkerConfigExtend ext = SpringContextUtil.getBean("freemarkerConfig",FreeMarkerConfigExtend.class);
/**獲取配置文件裏的 Configuration.settings 設到當前Cfg裏*/
Configuration vcfg = ext.getConfiguration();
Map<String,String> sets = vcfg.getSettings();
Set<String> keys = vcfg.getSharedVariableNames();
for (String key : keys) {
	TemplateModel value = vcfg.getSharedVariable(key);
	cfg.setSharedVariable(key, value);
}
Properties setting = new Properties(); 
setting.putAll(sets);
cfg.setSettings(setting);



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章