@Bean public FreeMarkerConfigurer freemarkerConfig() throws IOException, TemplateException { final FreeMarkerConfigurationFactory factory = new FreeMarkerConfigurationFactory(); // If overwritten use path of user if (isNotBlank(uaaProperties.getTemplatePath())) { final TemplateLoader templateLoader = getTemplateLoader(uaaProperties.getTemplatePath()); factory.setPreTemplateLoaders(templateLoader); } // Default configurations factory.setPostTemplateLoaders(getTemplateLoader("classpath:/templates/")); factory.setDefaultEncoding("UTF-8"); final FreeMarkerConfigurer result = new FreeMarkerConfigurer(); result.setConfiguration(factory.createConfiguration()); return result; }
@Bean @ConditionalOnMissingBean({FreeMarkerConfig.class, FreeMarkerViewResolver.class}) public FreeMarkerConfigurer freeMarkerConfigurer() { PluginFreeMarkerConfigurer configurer = new PluginFreeMarkerConfigurer(); applyProperties(configurer); String[] paths = this.properties.getTemplateLoaderPath(); // paths = ArrayUtils.add(paths, WEBFTLS_PATH); configurer.setTemplateLoaderPaths(paths); List<WithAnnotationBeanData<FreeMarkerViewTools>> tools = SpringUtils.getBeansWithAnnotation(applicationContext, FreeMarkerViewTools.class); tools.forEach(t->{ String name = t.getAnnotation().value(); if(StringUtils.isBlank(name)){ name = t.getBean().getClass().getSimpleName(); } configurer.setFreemarkerVariable(name, t.getBean()); logger.info("registered FreeMarkerViewTools : {}", name); }); return configurer; }
public EmailServiceImpl(FreeMarkerConfigurer freemarkerConfig, MessageSource messageSource, JavaMailSender javaMailSender, String baseURL, String defaultReplyTo, String sendToOM, String sendToVRK, int invitationExpirationDays, String testSendTo, boolean testConsoleOutput) { this.freemarkerConfig = freemarkerConfig; this.messageSource = messageSource; this.javaMailSender = javaMailSender; this.baseURL = baseURL; this.defaultReplyTo = defaultReplyTo; this.invitationExpirationDays = invitationExpirationDays; this.sendToOM = sendToOM; this.sendToVRK = sendToVRK; if (Strings.isNullOrEmpty(testSendTo)) { this.testSendTo = null; } else { this.testSendTo = testSendTo; } this.testConsoleOutput = testConsoleOutput; }
@Bean public FreeMarkerConfigurer getFreemarkerConfig() throws IOException, TemplateException { final FreeMarkerConfigurationFactory factory = new FreeMarkerConfigurationFactory(); factory.setTemplateLoaderPath("/WEB-INF/views/"); factory.setDefaultEncoding("UTF-8"); final Properties properties = new Properties(); properties.put("auto_import", "spring.ftl as spring"); properties.put("template_exception_handler", "rethrow"); factory.setFreemarkerSettings(properties); final Map<String, Object> sharedVariables = new HashMap<String, Object>(); sharedVariables.put("include", this.freemarkerIncludeDirective); factory.setFreemarkerVariables(sharedVariables); factory.setPreferFileSystemAccess(false); final FreeMarkerConfigurer result = new FreeMarkerConfigurer(); // FIXME factory not working // result.setConfiguration(factory.createConfiguration()); result.setTemplateLoaderPath("/WEB-INF/views/"); result.setFreemarkerVariables(sharedVariables); result.setFreemarkerSettings(properties); return result; }
/** * FreeMarker (ftl) configuration */ @Bean public FreeMarkerConfigurer freemarkerConfig() throws IOException, TemplateException { final FreeMarkerConfigurer result = new FreeMarkerConfigurer(); // template path result.setTemplateLoaderPath("/WEB-INF/ftl/"); result.setDefaultEncoding("UTF-8"); // static access final Version version = freemarker.template.Configuration.getVersion(); final BeansWrapper wrapper = new BeansWrapper(version); final TemplateHashModel statics = wrapper.getStaticModels(); final Map<String, Object> shared = new HashMap<>(); for (final Class<?> clazz : ElFunctions.staticClasses) { shared.put(clazz.getSimpleName(), statics.get(clazz.getName())); } result.setFreemarkerVariables(shared); return result; }
@Bean public FreeMarkerConfigurer configureFreemarker() { FreeMarkerConfigurer freeMarkerConfigurer = new FreeMarkerConfigurer(); Properties settings = new Properties(); settings.setProperty(freemarker.template.Configuration.TEMPLATE_EXCEPTION_HANDLER_KEY, "rethrow"); freeMarkerConfigurer.setFreemarkerSettings(settings); freeMarkerConfigurer.setTemplateLoaderPath(FreeMarkerProperties.DEFAULT_TEMPLATE_LOADER_PATH); return freeMarkerConfigurer; }
@Bean public FreeMarkerConfigurer freemarkerConfigurer() throws IOException { FreeMarkerConfigurer result = new FreeMarkerConfigurer(); if (nixmashModeEnabled) result.setTemplateLoaderPath("classpath:/nixmarker/"); else result.setTemplateLoaderPath("classpath:/freemarker/"); return result; }
/** * Register a FreeMarker view resolver with an empty default view name * prefix and a default suffix of ".ftl". * * <p><strong>Note</strong> that you must also configure FreeMarker by adding a * {@link org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer} bean. */ public UrlBasedViewResolverRegistration freeMarker() { if (this.applicationContext != null && !hasBeanOfType(FreeMarkerConfigurer.class)) { throw new BeanInitializationException("In addition to a FreeMarker view resolver " + "there must also be a single FreeMarkerConfig bean in this web application context " + "(or its parent): FreeMarkerConfigurer is the usual implementation. " + "This bean may be given any name."); } FreeMarkerRegistration registration = new FreeMarkerRegistration(); this.viewResolvers.add(registration.getViewResolver()); return registration; }
@Before public void setUp() { StaticWebApplicationContext context = new StaticWebApplicationContext(); context.registerSingleton("freeMarkerConfigurer", FreeMarkerConfigurer.class); context.registerSingleton("velocityConfigurer", VelocityConfigurer.class); context.registerSingleton("tilesConfigurer", TilesConfigurer.class); context.registerSingleton("groovyMarkupConfigurer", GroovyMarkupConfigurer.class); context.registerSingleton("scriptTemplateConfigurer", ScriptTemplateConfigurer.class); this.registry = new ViewResolverRegistry(); this.registry.setApplicationContext(context); this.registry.setContentNegotiationManager(new ContentNegotiationManager()); }
/** * 解析字符串模板 * * @param template * 字符串模板 * @param model * 数据 * @return 解析后内容 */ public static String process(String template, Map<String, ?> model) throws IOException, TemplateException { Configuration configuration = null; ApplicationContext applicationContext = SpringUtils.getApplicationContext(); if (applicationContext != null) { FreeMarkerConfigurer freeMarkerConfigurer = SpringUtils.getBean("freeMarkerConfigurer", FreeMarkerConfigurer.class); if (freeMarkerConfigurer != null) { configuration = freeMarkerConfigurer.getConfiguration(); } } return process(template, model, configuration); }
/** * html分页工具 * @param allList : html分页列表 * @param pagesize : 每页显示记录数量 * @param templatePathName : 模板页面,完整地址 (相相对于freeamrker配置根目录) * @param filePath : html文件,路径目录 --/-/ * @param index : html文件,默认前缀 index */ private static void generateHtmlPagination(FreeMarkerConfigurer freemarkerConfig, List<?> allList, Map<String, Object> paramMap,int pagesize, String templatePathName , String filePath , String index){ int allCount = allList!=null?allList.size():0; Map<String, Object> params = new HashMap<String, Object>(); params.put("pageNumAll", 1); params.put("pageNum", 1); params.put("filePath", filePath); params.put("index", index); if (MapUtils.isNotEmpty(paramMap)) { params.putAll(paramMap); } if (allCount > 0) { int pageNumAll = allCount%pagesize==0 ? allCount/pagesize : allCount/pagesize + 1; for (int pageNum = 1; pageNum <= pageNumAll; pageNum++) { params.put("pageNumAll", pageNumAll); params.put("pageNum", pageNum); int from = (pageNum-1)*pagesize; int to = (from + pagesize) <= allCount ? (from + pagesize) : allCount; params.put("pageList", allList.subList(from, to)); String fileName = (pageNum==1) ? index : (index + "_" + pageNum); HtmlTemplateUtil.generate(freemarkerConfig, params, templatePathName, filePath + fileName + ".html"); } } else { params.put("pageNumAll", 0); HtmlTemplateUtil.generate(freemarkerConfig, params, templatePathName, filePath + index + ".html"); } }
/** * 生成HTML字符串 * * @param content : 页面传参 */ public static String generateString(FreeMarkerConfigurer freemarkerConfig, Map<?, ?> content, String templateName) { String htmlText = ""; try { // 通过指定模板名获取FreeMarker模板实例 Template tpl = freemarkerConfig.getConfiguration().getTemplate(templateName); htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(tpl, content); } catch (Exception e) { e.printStackTrace(); } return htmlText; }
@Bean @ConditionalOnMissingBean(FreeMarkerConfig.class) public FreeMarkerConfigurer freeMarkerConfigurer() { FreeMarkerConfigurer configurer = new FreeMarkerConfigurer(); applyProperties(configurer); return configurer; }
@SuppressWarnings("deprecation") @Test public void customFreeMarkerSettings() { registerAndRefreshContext("spring.freemarker.settings.boolean_format:yup,nope"); assertThat(this.context.getBean(FreeMarkerConfigurer.class).getConfiguration() .getSetting("boolean_format")).isEqualTo("yup,nope"); }
@Test public void renderTemplate() throws Exception { registerAndRefreshContext(); FreeMarkerConfigurer freemarker = this.context .getBean(FreeMarkerConfigurer.class); StringWriter writer = new StringWriter(); freemarker.getConfiguration().getTemplate("message.ftl").process(this, writer); assertThat(writer.toString()).contains("Hello World"); }
@Bean public FreeMarkerConfigurer freemarkerConfig() { FreeMarkerConfigurer freeMarkerConfigurer = new FreeMarkerConfigurer(); freeMarkerConfigurer.setTemplateLoaderPath("/freemarker/view"); freeMarkerConfigurer.setDefaultEncoding("UTF-8"); freeMarkerConfigurer.setPreferFileSystemAccess(false); return freeMarkerConfigurer; }
@Bean public FreeMarkerConfigurer freeMarkerConfigurer() { final FreeMarkerConfigurer conf = new FreeMarkerConfigurer(); conf.setTemplateLoaderPath("/WEB-INF/views/"); conf.setDefaultEncoding("UTF-8"); return conf; }
@Bean public FreeMarkerConfigurer freeMarkerConfigurer() { final FreeMarkerConfigurer conf = new FreeMarkerConfigurer(); conf.setTemplateLoaderPath("/WEB-INF/views/mails/"); conf.setDefaultEncoding("UTF-8"); return conf; }
/** * Create a web application context suitable for FreeMarker unit testing. */ private static void configureKradWebApplicationContext() { MockServletContext sctx = new MockServletContext(); StaticWebApplicationContext ctx = new StaticWebApplicationContext(); ctx.setServletContext(sctx); MutablePropertyValues mpv = new MutablePropertyValues(); mpv.add("preferFileSystemAccess", false); mpv.add("templateLoaderPath", "/krad-web"); Properties props = new Properties(); props.put("number_format", "computer"); props.put("template_update_delay", "2147483647"); mpv.add("freemarkerSettings", props); ctx.registerSingleton("freemarkerConfig", FreeMarkerConfigurer.class, mpv); mpv = new MutablePropertyValues(); mpv.add("cache", true); mpv.add("prefix", ""); mpv.add("suffix", ".ftl"); ctx.registerSingleton("viewResolver", FreeMarkerViewResolver.class, mpv); ctx.registerSingleton("freeMarkerInputBootstrap", FreeMarkerInlineRenderBootstrap.class); ctx.refresh(); ctx.start(); sctx.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ctx); webApplicationContext = ctx; }
@SuppressWarnings("deprecation") @Test public void customFreeMarkerSettings() { registerAndRefreshContext("spring.freemarker.settings.boolean_format:yup,nope"); assertThat(this.context.getBean(FreeMarkerConfigurer.class).getConfiguration() .getSetting("boolean_format"), equalTo("yup,nope")); }
@Test public void renderTemplate() throws Exception { registerAndRefreshContext(); FreeMarkerConfigurer freemarker = this.context .getBean(FreeMarkerConfigurer.class); StringWriter writer = new StringWriter(); freemarker.getConfiguration().getTemplate("message.ftl").process(this, writer); assertThat(writer.toString(), containsString("Hello World")); }
/** * Configures Freemarker */ @Override public FreeMarkerConfigurer freeMarkerConfigurer() { FreeMarkerConfigurer result = super.freeMarkerConfigurer(); // Look up unknown templates in the FreemarkerTemplate repository result.setPostTemplateLoaders(new RepositoryTemplateLoader(dataService)); return result; }
protected Configuration createConfiguration(ServletContext servletContext) throws TemplateException { Configuration configuration = null; //Configuration configuration = super.createConfiguration(servletContext); ApplicationContext applicationContext = SpringHelper.getApplicationContext(servletContext); //configuration FreeMarkerConfigurer freeMarkerConfigurer = (FreeMarkerConfigurer) applicationContext .getBean(FREE_MARKER_CONFIGURER); configuration = freeMarkerConfigurer.getConfiguration(); //directive Map<String, TemplateDirectiveModel> beans = applicationContext .getBeansOfType(TemplateDirectiveModel.class); for (Map.Entry<String, TemplateDirectiveModel> entry : beans.entrySet()) { String key = entry.getKey(); TemplateDirectiveModel value = entry.getValue(); if (value instanceof TemplateDirectiveModel) { configuration.setSharedVariable(key, value); } } // return configuration; }
@Bean public FreeMarkerConfigurer freemarkerConfig() { FreeMarkerConfigurer config = new FreeMarkerConfigurer(); config.setDefaultEncoding("UTF-8"); String[] paths = {"/WEB-INF/freemarker/", "classpath:/freemarker/"}; config.setTemplateLoaderPaths(paths); Map<String, Object> variables = Maps.newHashMap(); variables.put("xml_escape", fmXmlEscape()); config.setFreemarkerVariables(variables); return config; }
@Bean public BeansWrapper freemarkerObjectWrapper(FreeMarkerConfigurer freeMarkerConfigurer) { boolean testFreemarkerShowErrorsOnPage = env.getProperty(PropertyNames.testFreemarkerShowErrorsOnPage, Boolean.class, TEST_FREEMARKER_SHOW_ERRORS_ON_PAGE_DEFAULT); if (!testFreemarkerShowErrorsOnPage) { freeMarkerConfigurer.getConfiguration().setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); } return (BeansWrapper) freeMarkerConfigurer.getConfiguration().getObjectWrapper(); }
@Bean public EmailService emailService(FreeMarkerConfigurer freeMarkerConfigurer) { String baseURL = env.getRequiredProperty(PropertyNames.baseURL); String defaultReplyTo = env.getRequiredProperty(PropertyNames.emailDefaultReplyTo); String sendToOM = env.getRequiredProperty(PropertyNames.emailSendToOM); String sendToVRK = env.getRequiredProperty(PropertyNames.emailSendToVRK); int invitationExpirationDays = env.getRequiredProperty(PropertyNames.invitationExpirationDays, Integer.class); String testSendTo = env.getProperty(PropertyNames.testEmailSendTo); boolean testConsoleOutput = env.getProperty(PropertyNames.testEmailConsoleOutput, Boolean.class, TEST_EMAIL_CONSOLE_OUTPUT_DEFAULT); return new EmailServiceImpl(freeMarkerConfigurer, messageSource(), javaMailSender(), baseURL, defaultReplyTo, sendToOM, sendToVRK, invitationExpirationDays, testSendTo, testConsoleOutput); }
/** * Overrides Spring Boot's {@link FreeMarkerAutoConfiguration} to prefer using a * {@link SpringTemplateLoader} instead of the file system. This corrects an issue * where Spring Boot may use an empty 'templates' file resource to resolve templates * instead of the packaged Hystrix classpath templates. * @return FreeMarker configuration */ @Bean public FreeMarkerConfigurer freeMarkerConfigurer() { FreeMarkerConfigurer configurer = new FreeMarkerConfigurer(); configurer.setTemplateLoaderPaths(DEFAULT_TEMPLATE_LOADER_PATH); configurer.setDefaultEncoding(DEFAULT_CHARSET); configurer.setPreferFileSystemAccess(false); return configurer; }
public static String process(String template, Map model) { Configuration configuration = null; FreeMarkerConfigurer freemarkerconfigurer = (FreeMarkerConfigurer)SpringUtil.getBean("freeMarkerConfigurer", FreeMarkerConfigurer.class); if(freemarkerconfigurer != null) configuration = freemarkerconfigurer.getConfiguration(); return process(template, model, configuration); }
public void setFreeMarkerConfigurer(FreeMarkerConfigurer freeMarkerConfigurer) { this.freeMarkerConfigurer = freeMarkerConfigurer; Configuration configuration = freeMarkerConfigurer.getConfiguration(); configuration.setSharedVariable("millisToDateTime", new MillisToDateTimeFreemarkerModel()); configuration.setSharedVariable("empty", new EmptyFreemarkerModel()); configuration.setSharedVariable("escapeHtml", new EscapeHtmlFreemarkerModel()); configuration.setSharedVariable("unescapeHtml", new UnescapeHtmlFreemarkerModel()); }
@Bean public FreeMarkerConfigurer freeMarkerConfigurer () { FreeMarkerConfigurer configurer = new FreeMarkerConfigurer (); configurer.setTemplateLoaderPath ("classpath:"); configurer.setPreferFileSystemAccess (false); return configurer; }
/** * Configure freemarker. All freemarker templates should be on the classpath in a package called 'freemarker' */ @Bean public FreeMarkerConfigurer freeMarkerConfigurer() { FreeMarkerConfigurer result = new FreeMarkerConfigurer() { @Override protected void postProcessConfiguration(Configuration config) throws IOException, TemplateException { config.setObjectWrapper(new MolgenisFreemarkerObjectWrapper(VERSION_2_3_23)); } }; result.setPreferFileSystemAccess(false); result.setTemplateLoaderPath("classpath:/templates/"); result.setDefaultEncoding("UTF-8"); Properties freemarkerSettings = new Properties(); freemarkerSettings.setProperty(Configuration.LOCALIZED_LOOKUP_KEY, Boolean.FALSE.toString()); result.setFreemarkerSettings(freemarkerSettings); Map<String, Object> freemarkerVariables = Maps.newHashMap(); freemarkerVariables.put("limit", new LimitMethod()); freemarkerVariables.put("hasPermission", new HasPermissionDirective(permissionService)); freemarkerVariables.put("notHasPermission", new NotHasPermissionDirective(permissionService)); addFreemarkerVariables(freemarkerVariables); result.setFreemarkerVariables(freemarkerVariables); return result; }
@Bean public FreeMarkerConfigurer freeMarkerConfigurer() { FreeMarkerConfigurer configurer = new FreeMarkerConfigurer(); configurer.setTemplateLoaderPath("classpath:/templates/"); configurer.setDefaultEncoding("UTF-8"); return configurer; }
@Bean public FreeMarkerConfigurer freemarkerConfig() throws IOException, TemplateException { FreeMarkerConfigurer freeMarkerConfigurer = new FreeMarkerConfigurer(); freeMarkerConfigurer.setConfiguration(new freemarker.template.Configuration(freemarker.template.Configuration.VERSION_2_3_22) {{ setTemplateLoader(new MultiTemplateLoader( new TemplateLoader[]{ new ClassTemplateLoader(FreeMarkerConfig.class, "/") } )); setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); setWhitespaceStripping(true); }}); return freeMarkerConfigurer; }
@Bean FreeMarkerConfigurer freeMarkerConfigurer() { FreeMarkerConfigurer configurer = new FreeMarkerConfigurer(); configurer.setTemplateLoaderPath("classpath:META-INF/freemarker"); return configurer; }