Java Code Examples for com.github.jknack.handlebars.Handlebars#compile()
The following examples show how to use
com.github.jknack.handlebars.Handlebars#compile() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HandlebarsEngineAdapter.java From openapi-generator with Apache License 2.0 | 5 votes |
public String compileTemplate(TemplatingExecutor executor, Map<String, Object> bundle, String templateFile) throws IOException { TemplateLoader loader = new AbstractTemplateLoader() { @Override public TemplateSource sourceAt(String location) { return findTemplate(executor, location); } }; Context context = Context .newBuilder(bundle) .resolver( MapValueResolver.INSTANCE, JavaBeanValueResolver.INSTANCE, FieldValueResolver.INSTANCE) .build(); Handlebars handlebars = new Handlebars(loader); handlebars.registerHelperMissing((obj, options) -> { LOGGER.warn(String.format(Locale.ROOT, "Unregistered helper name '%s', processing template:\n%s", options.helperName, options.fn.text())); return ""; }); handlebars.registerHelper("json", Jackson2Helper.INSTANCE); StringHelpers.register(handlebars); handlebars.registerHelpers(ConditionalHelpers.class); handlebars.registerHelpers(org.openapitools.codegen.templating.handlebars.StringHelpers.class); Template tmpl = handlebars.compile(templateFile); return tmpl.apply(context); }
Example 2
Source File: ReusingTemplatesUnitTest.java From tutorials with MIT License | 5 votes |
@Test public void whenOtherTemplateIsReferenced_ThenCanReuse() throws IOException { Handlebars handlebars = new Handlebars(templateLoader); Template template = handlebars.compile("page"); Person person = new Person(); person.setName("Baeldung"); String templateString = template.apply(person); assertThat(templateString) .contains("<h4>Hi Baeldung!</h4>", "<p>This is the page Baeldung</p>"); }
Example 3
Source File: SingularityExecutorModule.java From Singularity with Apache License 2.0 | 5 votes |
@Provides @Singleton @Named(LOGROTATE_CRON_TEMPLATE) public Template providesLogrotateCronTemplate(Handlebars handlebars) throws IOException { return handlebars.compile(LOGROTATE_CRON_TEMPLATE); }
Example 4
Source File: BuiltinHelperUnitTest.java From tutorials with MIT License | 5 votes |
@Test public void whenUsedWith_ThenContextChanges() throws IOException { Handlebars handlebars = new Handlebars(templateLoader); Template template = handlebars.compile("with"); Person person = getPerson("Baeldung"); person.getAddress().setStreet("World"); String templateString = template.apply(person); assertThat(templateString).contains("<h4>I live in World</h4>"); }
Example 5
Source File: TestTemplatesCompile.java From arcusplatform with Apache License 2.0 | 5 votes |
@Test public void testTemplatesCompile() throws Exception { TemplateLoader loader = new IrisResourceLoader("templates", 0); Handlebars handlebars = new Handlebars(loader) .registerHelper(EnumHelper.NAME, EnumHelper.INSTANCE) .registerHelpers(HandlebarsHelpersSource.class) .registerHelper(IfEqualHelper.NAME, IfEqualHelper.INSTANCE) .registerHelpers(StringHelpers.class); Validator v = new Validator(); String templateDir = Resources .getResource("templates") .getUri() .toURL() .getPath(); for(File template: new File(templateDir).listFiles((file) -> file != null && file.getName() != null && file.getName().endsWith(".hbs"))) { try { String name = template.getName(); name = name.substring(0, name.length() - 4); Template tpl = handlebars.compile(name); if(name.endsWith("-email")) { // TODO validate email xml continue; } String body = tpl.apply(Context.newContext(Collections.emptyMap())); JSON.fromJson(body, Map.class); } catch(Exception e) { e.printStackTrace(); v.error("Failed to compile: " + template.getName() + " -- " + e.getMessage()); } } v.throwIfErrors(); }
Example 6
Source File: HandlebarsHelper.java From spring-cloud-release with Apache License 2.0 | 5 votes |
public static Template template(String templateName) { try { Handlebars handlebars = new Handlebars( new ClassPathTemplateLoader("/templates/spring-cloud/")); handlebars.registerHelper("replace", StringHelpers.replace); handlebars.registerHelper("capitalizeFirst", StringHelpers.capitalizeFirst); return handlebars.compile(templateName); } catch (IOException e) { throw new IllegalStateException(e); } }
Example 7
Source File: PASystemImpl.java From sakai with Educational Community License v2.0 | 5 votes |
@Override public String getFooter() { StringBuilder result = new StringBuilder(); I18n i18n = getI18n(this.getClass().getClassLoader(), "org.sakaiproject.pasystem.impl.i18n.pasystem"); Handlebars handlebars = loadHandleBars(i18n); Session session = SessionManager.getCurrentSession(); Map<String, Object> context = new HashMap<String, Object>(); try { Template template = handlebars.compile("templates/shared_footer"); context.put("portalCDNQuery", PortalUtils.getCDNQuery()); context.put("sakai_csrf_token", session.getAttribute("sakai.csrf.token")); result.append(template.apply(context)); } catch (IOException e) { log.warn("IOException while getting footer", e); return ""; } result.append(getBannersFooter(handlebars, context)); result.append(getPopupsFooter(handlebars, context)); result.append(getTimezoneCheckFooter(handlebars, context)); return result.toString(); }
Example 8
Source File: PASystemImpl.java From sakai with Educational Community License v2.0 | 5 votes |
private String getPopupsFooter(Handlebars handlebars, Map<String, Object> context) { Session session = SessionManager.getCurrentSession(); User currentUser = UserDirectoryService.getCurrentUser(); if (currentUser == null || currentUser.getId() == null || "".equals(currentUser.getId())) { return ""; } try { if (session.getAttribute(POPUP_SCREEN_SHOWN) == null) { Popup popup = new PopupForUser(currentUser).getPopup(); if (popup.isActiveNow()) { context.put("popupTemplate", popup.getTemplate()); context.put("popupUuid", popup.getUuid()); context.put("popup", true); if (currentUser.getId() != null) { // Delivered! session.setAttribute(POPUP_SCREEN_SHOWN, "true"); } } } Template template = handlebars.compile("templates/popup_footer"); return template.apply(context); } catch (IOException | MissingUuidException e) { log.warn("IOException while getting popups footer", e); return ""; } }
Example 9
Source File: BuiltinHelperUnitTest.java From tutorials with MIT License | 5 votes |
@Test public void whenUsedWithMustacheStyle_ThenContextChanges() throws IOException { Handlebars handlebars = new Handlebars(templateLoader); Template template = handlebars.compile("with_mustache"); Person person = getPerson("Baeldung"); person.getAddress().setStreet("World"); String templateString = template.apply(person); assertThat(templateString).contains("<h4>I live in World</h4>"); }
Example 10
Source File: PASystemImpl.java From sakai with Educational Community License v2.0 | 5 votes |
private String getPopupsFooter(Handlebars handlebars, Map<String, Object> context) { Session session = SessionManager.getCurrentSession(); User currentUser = UserDirectoryService.getCurrentUser(); if (currentUser == null || currentUser.getId() == null || "".equals(currentUser.getId())) { return ""; } try { if (session.getAttribute(POPUP_SCREEN_SHOWN) == null) { Popup popup = new PopupForUser(currentUser).getPopup(); if (popup.isActiveNow()) { context.put("popupTemplate", popup.getTemplate()); context.put("popupUuid", popup.getUuid()); context.put("popup", true); if (currentUser.getId() != null) { // Delivered! session.setAttribute(POPUP_SCREEN_SHOWN, "true"); } } } Template template = handlebars.compile("templates/popup_footer"); return template.apply(context); } catch (IOException | MissingUuidException e) { log.warn("IOException while getting popups footer", e); return ""; } }
Example 11
Source File: BasicUsageUnitTest.java From tutorials with MIT License | 5 votes |
@Test public void whenClasspathTemplateLoaderIsGiven_ThenSearchesClasspathWithPrefixSuffix() throws IOException { TemplateLoader loader = new ClassPathTemplateLoader("/handlebars", ".html"); Handlebars handlebars = new Handlebars(loader); Template template = handlebars.compile("greeting"); Person person = getPerson("Baeldung"); String templateString = template.apply(person); assertThat(templateString).isEqualTo("Hi Baeldung!"); }
Example 12
Source File: BuiltinHelperUnitTest.java From tutorials with MIT License | 5 votes |
@Test public void whenUsedEach_ThenIterates() throws IOException { Handlebars handlebars = new Handlebars(templateLoader); Template template = handlebars.compile("each"); Person person = getPerson("Baeldung"); Person friend1 = getPerson("Java"); Person friend2 = getPerson("Spring"); person.getFriends().add(friend1); person.getFriends().add(friend2); String templateString = template.apply(person); assertThat(templateString) .contains("<span>Java is my friend.</span>", "<span>Spring is my friend.</span>"); }
Example 13
Source File: PASystemImpl.java From sakai with Educational Community License v2.0 | 5 votes |
private String getBannersFooter(Handlebars handlebars, Map<String, Object> context) { try { Template template = handlebars.compile("templates/banner_footer"); context.put("bannerJSON", getActiveBannersJSON()); return template.apply(context); } catch (IOException e) { log.warn("IOException while getting banners footer", e); return ""; } }
Example 14
Source File: SingularityExecutorModule.java From Singularity with Apache License 2.0 | 4 votes |
@Provides @Singleton @Named(RUNNER_TEMPLATE) public Template providesRunnerTemplate(Handlebars handlebars) throws IOException { return handlebars.compile(RUNNER_TEMPLATE); }
Example 15
Source File: PASystemServlet.java From sakai with Educational Community License v2.0 | 4 votes |
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { checkAccessControl(); I18n i18n = paSystem.getI18n(this.getClass().getClassLoader(), "org.sakaiproject.pasystem.tool.i18n.pasystem"); response.setHeader("Content-Type", "text/html"); URL toolBaseURL = determineBaseURL(); Handlebars handlebars = loadHandlebars(toolBaseURL, i18n); try { Template template = handlebars.compile("org/sakaiproject/pasystem/tool/views/layout"); Map<String, Object> context = new HashMap<String, Object>(); context.put("baseURL", toolBaseURL); context.put("layout", true); context.put("skinRepo", ServerConfigurationService.getString("skin.repo", "")); context.put("randomSakaiHeadStuff", request.getAttribute("sakai.html.head")); Handler handler = handlerForRequest(request); Map<String, List<String>> messages = loadFlashMessages(); handler.handle(request, response, context); storeFlashMessages(handler.getFlashMessages()); if (handler.hasRedirect()) { response.sendRedirect(toolBaseURL + handler.getRedirect()); } else { context.put("flash", messages); context.put("errors", handler.getErrors().toList()); if (Boolean.TRUE.equals(context.get("layout"))) { response.getWriter().write(template.apply(context)); } } } catch (IOException e) { log.warn("Write failed", e); } }
Example 16
Source File: PASystemServlet.java From sakai with Educational Community License v2.0 | 4 votes |
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { checkAccessControl(); I18n i18n = paSystem.getI18n(this.getClass().getClassLoader(), "org.sakaiproject.pasystem.tool.i18n.pasystem"); response.setHeader("Content-Type", "text/html"); URL toolBaseURL = determineBaseURL(); Handlebars handlebars = loadHandlebars(toolBaseURL, i18n); try { Template template = handlebars.compile("org/sakaiproject/pasystem/tool/views/layout"); Map<String, Object> context = new HashMap<String, Object>(); context.put("baseURL", toolBaseURL); context.put("layout", true); context.put("skinRepo", ServerConfigurationService.getString("skin.repo", "")); context.put("randomSakaiHeadStuff", request.getAttribute("sakai.html.head")); Handler handler = handlerForRequest(request); Map<String, List<String>> messages = loadFlashMessages(); handler.handle(request, response, context); storeFlashMessages(handler.getFlashMessages()); if (handler.hasRedirect()) { response.sendRedirect(toolBaseURL + handler.getRedirect()); } else { context.put("flash", messages); context.put("errors", handler.getErrors().toList()); if (Boolean.TRUE.equals(context.get("layout"))) { response.getWriter().write(template.apply(context)); } } } catch (IOException e) { log.warn("Write failed", e); } }
Example 17
Source File: SingularityExecutorModule.java From Singularity with Apache License 2.0 | 4 votes |
@Provides @Singleton @Named(DOCKER_TEMPLATE) public Template providesDockerTempalte(Handlebars handlebars) throws IOException { return handlebars.compile(DOCKER_TEMPLATE); }
Example 18
Source File: SingularityExecutorConfigurationTest.java From Singularity with Apache License 2.0 | 4 votes |
@Test public void itProperlyGeneratesTwoLogrotateConfigs() throws Exception { Handlebars handlebars = new Handlebars(); Template hourlyTemplate = handlebars.compile( SingularityExecutorModule.LOGROTATE_HOURLY_TEMPLATE ); Template nonHourlyTemplate = handlebars.compile( SingularityExecutorModule.LOGROTATE_TEMPLATE ); LogrotateTemplateContext context = mock(LogrotateTemplateContext.class); List<LogrotateAdditionalFile> testExtraFiles = new ArrayList<>(); List<LogrotateAdditionalFile> testExtraFilesHourly = new ArrayList<>(); testExtraFiles.add( new LogrotateAdditionalFile( "/tmp/testfile.txt", "txt", "%Y%m%d", Optional.of(SingularityExecutorLogrotateFrequency.MONTHLY) ) ); testExtraFilesHourly.add( new LogrotateAdditionalFile( "/tmp/testfile-hourly.txt", "txt", "%Y%m%d", Optional.of(SingularityExecutorLogrotateFrequency.HOURLY) ) ); doReturn(SingularityExecutorLogrotateFrequency.WEEKLY.getLogrotateValue()) .when(context) .getLogrotateFrequency(); doReturn(testExtraFiles).when(context).getExtrasFiles(); doReturn(testExtraFilesHourly).when(context).getExtrasFilesHourly(); doReturn(false).when(context).isGlobalLogrotateHourly(); // This sample output template, when copied into a staged Mesos slave and run with `logrotate -d <configFileName>` // confirms that a testfile.txt at the /tmp/testfile.txt will be cycled daily instead of weekly String hourlyOutput = hourlyTemplate.apply(context); String nonHourlyOutput = nonHourlyTemplate.apply(context); // Assert that our config has both weekly and daily scopes, and that daily occurs second (thus overrides weekly // in the /tmp/testfile-hourly.txt YAML object). // Admittedly, YAML serialization would be better, but given this code doesn't actually test much without // a binary of `logrotate` to run against, it's not a big deal. assertThat(hourlyOutput.contains("weekly")).isTrue(); assertThat(hourlyOutput.contains("daily")).isTrue(); assertThat(hourlyOutput.indexOf("daily")) .isGreaterThan(hourlyOutput.indexOf("weekly")); // Assert that our config has both weekly and monthly scopes, and that monthly occurs second (thus overrides weekly // in the /tmp/testfile.txt YAML object). assertThat(nonHourlyOutput.contains("weekly")).isTrue(); assertThat(nonHourlyOutput.contains("monthly")).isTrue(); assertThat(nonHourlyOutput.indexOf("monthly")) .isGreaterThan(hourlyOutput.indexOf("weekly")); }
Example 19
Source File: TagServiceServlet.java From sakai with Educational Community License v2.0 | 4 votes |
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { checkAccessControl(); I18n i18n = tagService.getI18n(this.getClass().getClassLoader(), "org.sakaiproject.tags.tool.i18n.tagservice"); response.setHeader("Content-Type", "text/html"); URL toolBaseURL = determineBaseURL(); Handlebars handlebars = loadHandlebars(toolBaseURL, i18n); try { Template template = handlebars.compile("org/sakaiproject/tags/tool/views/layout"); Map<String, Object> context = new HashMap<>(); context.put("baseURL", toolBaseURL); context.put("layout", true); context.put("skinRepo", serverConfigurationService.getString("skin.repo", "")); context.put("randomSakaiHeadStuff", request.getAttribute("sakai.html.head")); Handler handler = handlerForRequest(request); Map<String, List<String>> messages = loadFlashMessages(); handler.handle(request, response, context); storeFlashMessages(handler.getFlashMessages()); if (handler.hasRedirect()) { response.sendRedirect(toolBaseURL + handler.getRedirect()); } else { context.put("flash", messages); context.put("errors", handler.getErrors().toList()); if (Boolean.TRUE.equals(context.get("layout"))) { response.getWriter().write(template.apply(context)); } } } catch (IOException e) { log.warn("Write failed", e); } }
Example 20
Source File: ViewHelper.java From fess with Apache License 2.0 | 4 votes |
public String createCacheContent(final Map<String, Object> doc, final String[] queries) { final FessConfig fessConfig = ComponentUtil.getFessConfig(); final FileTemplateLoader loader = new FileTemplateLoader(ResourceUtil.getViewTemplatePath().toFile()); final Handlebars handlebars = new Handlebars(loader); Locale locale = ComponentUtil.getRequestManager().getUserLocale(); if (locale == null) { locale = Locale.ENGLISH; } String url = DocumentUtil.getValue(doc, fessConfig.getIndexFieldUrl(), String.class); if (url == null) { url = ComponentUtil.getMessageManager().getMessage(locale, "labels.search_unknown"); } doc.put(fessConfig.getResponseFieldUrlLink(), getUrlLink(doc)); String createdStr; final Date created = DocumentUtil.getValue(doc, fessConfig.getIndexFieldCreated(), Date.class); if (created != null) { final SimpleDateFormat sdf = new SimpleDateFormat(CoreLibConstants.DATE_FORMAT_ISO_8601_EXTEND); createdStr = sdf.format(created); } else { createdStr = ComponentUtil.getMessageManager().getMessage(locale, "labels.search_unknown"); } doc.put(CACHE_MSG, ComponentUtil.getMessageManager().getMessage(locale, "labels.search_cache_msg", url, createdStr)); doc.put(QUERIES, queries); String cache = DocumentUtil.getValue(doc, fessConfig.getIndexFieldCache(), String.class); if (cache != null) { final String mimetype = DocumentUtil.getValue(doc, fessConfig.getIndexFieldMimetype(), String.class); if (!ComponentUtil.getFessConfig().isHtmlMimetypeForCache(mimetype)) { cache = StringEscapeUtils.escapeHtml4(cache); } cache = ComponentUtil.getPathMappingHelper().replaceUrls(cache); if (queries != null && queries.length > 0) { doc.put(HL_CACHE, replaceHighlightQueries(cache, queries)); } else { doc.put(HL_CACHE, cache); } } else { doc.put(fessConfig.getIndexFieldCache(), StringUtil.EMPTY); doc.put(HL_CACHE, StringUtil.EMPTY); } try { final Template template = handlebars.compile(cacheTemplateName); final Context hbsContext = Context.newContext(doc); return template.apply(hbsContext); } catch (final Exception e) { logger.warn("Failed to create a cache response.", e); } return null; }