Java Code Examples for com.github.jknack.handlebars.Template#apply()

The following examples show how to use com.github.jknack.handlebars.Template#apply() . 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: HandlebarsViewEngine.java    From ozark with Apache License 2.0 6 votes vote down vote up
@Override
public void processView(ViewEngineContext context) throws ViewEngineException {

    Map<String, Object> model = new HashMap<>(context.getModels().asMap());
    model.put("request", context.getRequest(HttpServletRequest.class));
    
    Charset charset = resolveCharsetAndSetContentType(context);

    try (Writer writer = new OutputStreamWriter(context.getOutputStream(), charset);
         
        InputStream resourceAsStream = servletContext.getResourceAsStream(resolveView(context));
        InputStreamReader in = new InputStreamReader(resourceAsStream, "UTF-8");
        BufferedReader bufferedReader = new BufferedReader(in);) {

        String viewContent = bufferedReader.lines().collect(Collectors.joining());

        Template template = handlebars.compileInline(viewContent);
        template.apply(model, writer);
        
    } catch (IOException e) {
        throw new ViewEngineException(e);
    }
}
 
Example 2
Source File: ObjCProcessor.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
protected void applyTemplates(List<CapabilityDefinition> capabilities,
      List<ServiceDefinition> services,
      List<ProtocolDefinition> protocols) throws IOException {
   Map<String, List<? extends Definition>> definitions
      = new HashMap<String, List<? extends Definition>>();
   definitions.put("capabilities", capabilities);
   definitions.put("services", services);
   definitions.put("protocols", protocols);

   Template template = handlebars.compile(templateName);
   OutputStreamWriter writer = new OutputStreamWriter(System.out);
   try {
      template.apply(definitions, writer);
      writer.flush();
   }
   finally {
      writer.close();
   }
}
 
Example 3
Source File: TemplateGenerator.java    From spring-cloud-release with Apache License 2.0 6 votes vote down vote up
File generate(List<Project> projects,
		List<ConfigurationProperty> configurationProperties) {
	PathMatchingResourcePatternResolver resourceLoader = new PathMatchingResourcePatternResolver();
	try {
		Resource[] resources = resourceLoader
				.getResources("templates/spring-cloud/*.hbs");
		List<TemplateProject> templateProjects = templateProjects(projects);
		for (Resource resource : resources) {
			File templateFile = resource.getFile();
			File outputFile = new File(outputFolder, renameTemplate(templateFile));
			Template template = template(templateFile.getName().replace(".hbs", ""));
			Map<String, Object> map = new HashMap<>();
			map.put("projects", projects);
			map.put("springCloudProjects", templateProjects);
			map.put("properties", configurationProperties);
			String applied = template.apply(map);
			Files.write(outputFile.toPath(), applied.getBytes());
			info("Successfully rendered [" + outputFile.getAbsolutePath() + "]");
		}
	}
	catch (IOException e) {
		throw new IllegalStateException(e);
	}
	return outputFolder;
}
 
Example 4
Source File: CucumberReportBuilder.java    From bootstraped-multi-test-results-report with MIT License 5 votes vote down vote up
private void writeFeatureSummaryReports() throws IOException {
    Template template = bars.compile(FEATURE_SUMMARY_REPORT);
    for (Feature feature : getProcessedFeatures()) {
        String generatedFeatureHtmlContent = template.apply(feature);
        // generatedFeatureSummaryReports.put(feature.getUniqueID(), generatedFeatureHtmlContent);
        FileUtils.writeStringToFile(new File(REPORTS_SUMMARY_PATH + feature.getUniqueID() + ".html"),
            generatedFeatureHtmlContent);
    }
}
 
Example 5
Source File: PASystemImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
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 6
Source File: ThrottlePolicyGenerator.java    From product-microgateway with Apache License 2.0 5 votes vote down vote up
private String getPolicyInitContent(ThrottlePolicyInitializer object)
        throws IOException {
    Template template = CodegenUtils.compileTemplate(GeneratorConstants.DEFAULT_TEMPLATE_DIR,
            GeneratorConstants.THROTTLE_POLICY_INIT_TEMPLATE_NAME);
    Context context = Context.newBuilder(object)
            .resolver(MapValueResolver.INSTANCE, JavaBeanValueResolver.INSTANCE, FieldValueResolver.INSTANCE)
            .build();

    return template.apply(context);
}
 
Example 7
Source File: ThrottlePolicyGenerator.java    From product-microgateway with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieve generated source content as a String value.
 *
 * @param object context to be used by template engine
 * @return String with populated template
 * @throws IOException when template population fails
 */
private String getContent(ThrottlePolicy object) throws IOException {
    Template template = CodegenUtils.compileTemplate(GeneratorConstants.DEFAULT_TEMPLATE_DIR,
            GeneratorConstants.THROTTLE_POLICY_TEMPLATE_NAME);
    Context context = Context.newBuilder(object)
            .resolver(MapValueResolver.INSTANCE, JavaBeanValueResolver.INSTANCE, FieldValueResolver.INSTANCE)
            .build();

    return template.apply(context);
}
 
Example 8
Source File: HandlebarsTemplateEngine.java    From commercetools-sunrise-java with Apache License 2.0 5 votes vote down vote up
@Override
public String render(final String templateName, final TemplateContext templateContext) {
    final Template template = compileTemplate(templateName);
    final Context context = contextFactory.create(handlebars, templateName, templateContext);
    try {
        LOGGER.debug("Rendering template " + templateName);
        return template.apply(context);
    } catch (IOException e) {
        throw new TemplateRenderException("Context could not be applied to template " + templateName, e);
    }
}
 
Example 9
Source File: StringHelpersTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
private void evaluate(HashMap<String, Object> data, String template, String expect) throws IOException {

        Context context = Context
                .newBuilder(data)
                .resolver(
                        FieldValueResolver.INSTANCE)
                .build();

        Template tmpl = handlebars.compileInline(template);
        String actual = tmpl.apply(context);
        assertEquals(actual, expect);
    }
 
Example 10
Source File: HandlebarsEngineAdapter.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
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 11
Source File: PASystemImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
private String getTimezoneCheckFooter(Handlebars handlebars, Map<String, Object> context) {
    if (ServerConfigurationService.getBoolean("pasystem.timezone-check", true)) {

        try {
            Template template = handlebars.compile("templates/timezone_footer");

            return template.apply(context);
        } catch (IOException e) {
            log.warn("Timezone footer failed", e);
            return "";
        }
    } else {
        return "";
    }
}
 
Example 12
Source File: TestTemplatesCompile.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@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 13
Source File: JavaProcessor.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
public String apply(Object context, Template template, String fileName)
throws IOException {
   try {
      String java = template.apply(context);
      writeFile(fileName, java);
      logger.info("Class generated [{}]", fileName);
      return fileName;
      
   } catch (IOException e) {
      logger.error("Could not create java file for " + context, e);
      throw e;
   }
}
 
Example 14
Source File: HandlebarsTemplateEngine.java    From spark-template-engines with Apache License 2.0 5 votes vote down vote up
@Override
public String render(ModelAndView modelAndView) {
    String viewName = modelAndView.getViewName();
    try {
        Template template = handlebars.compile(viewName);
        return template.apply(modelAndView.getModel());
    } catch (IOException e) {
        throw new RuntimeIOException(e);
    }
}
 
Example 15
Source File: HTMLProcessor.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
public void createIndexFrame(DefinitionIndex index) throws IOException {
   try {
      Template template = handlebars.compile("capindex");
      String html = template.apply(index);
      writeFile("capability-index.html", html);
      logger.info("Index frame created");
   } catch (IOException e) {
      logger.error("Could not create capability index page");
      throw e;
   }
}
 
Example 16
Source File: HTMLProcessor.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
public void createFrameSet(DefinitionIndex index) throws IOException {
   try {
      Template template = handlebars.compile("capframe");
      String html = template.apply(index.getCapabilities().get(0).getHtmlFile());
      writeFile("index.html", html);
      logger.info("Frameset created");
   } catch (IOException e) {
      logger.error("Could not create fameset page");
      throw e;
   }
}
 
Example 17
Source File: BackboneViewProcessor.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
public String apply(Object context, Template template, String fileName) throws IOException {
    try {
        String java = template.apply(context);
        writeFile(fileName, java);
        logger.info("Class generated [{}]", fileName);
        return fileName;

    } catch (IOException e) {
        logger.error("Could not create capability file for " + context, e);
        throw e;
    }
}
 
Example 18
Source File: PASystemImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
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 19
Source File: TestMessages.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
   public String render(String templateId, Object context) {
Template template;
      try {
       template = handlebars.compileInline(templates.get(templateId));
       return template.apply(context);
      } catch (IOException e) {
       Assert.fail("Unable to apply template");
       return null;
      }			
   }
 
Example 20
Source File: TagTemplateProcessor.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
private String generateTemplateWithParameters(String sourceTemplate, TagPreparationObject model)
        throws IOException {
    Template template = handlebars.compileInline(sourceTemplate, HandlebarTemplate.DEFAULT_PREFIX.key(), HandlebarTemplate.DEFAULT_POSTFIX.key());
    return template.apply(prepareTemplateObject(model));
}