public class UserDirective implements TemplateDirectiveModel { public static final String ID = "id"; @Autowired protected AdminUserService adminUserService; @Override public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { if (loopVars.length < 1) { throw new TemplateModelException("Loop variable is required."); } if (body == null) { throw new RuntimeException("missing body"); } Long id = Freemarkers.getLong(params,ID); AdminUser adminUser = null; if(id != null){ adminUser = adminUserService.findUniqueBy("id",id); } loopVars[0] = env.getObjectWrapper().wrap(adminUser); body.render(env.getOut()); } }
<bean id="User" class="com.sr.fore.manage.web.core.directive.UserDirective"/>
<property name="freemarkerSettings"> <props> <prop key="tag_syntax">square_bracket</prop> <prop key="template_update_delay">2</prop> <prop key="defaultEncoding">UTF-8</prop> <prop key="url_escaping_charset">UTF-8</prop> <prop key="localized_lookup">false</prop> <prop key="locale">zh_CN</prop> <prop key="boolean_format">true,false</prop> <prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop> <prop key="date_format">yyyy-MM-dd</prop> <prop key="time_format">HH:mm:ss</prop> <prop key="number_format">0.###</prop> <prop key="whitespace_stripping">true</prop> <prop key="auto_import">/spring.ftl as s</prop> </props> </property>
FreeMarkerConfigurationFactory setFreemarkerVariables(Map<String, Object> variables)
[#escape x as (x)!?html] <!DOCTYPE html> <html> <head> <title></title> </head> <body> [@User id = "1";user] <table> <thead> ${user.userName} </thead> </table> [/@User] </body> </html> [/#escape]
freemarkerVariables 是一个map对象,键对应标签名称,值对应xxxDirective