Java Code Examples for com.github.jknack.handlebars.Handlebars#registerHelper()

The following examples show how to use com.github.jknack.handlebars.Handlebars#registerHelper() . 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: CodegenUtils.java    From product-microgateway with Apache License 2.0 6 votes vote down vote up
/**
 * Compile given template.
 *
 * @param defaultTemplateDir template directory
 * @param templateName template name
 * @return Generated template
 * @throws IOException if file read went wrong
 */
public static Template compileTemplate(String defaultTemplateDir, String templateName) throws IOException {
    String templatesDirPath = System.getProperty(GeneratorConstants.TEMPLATES_DIR_PATH_KEY, defaultTemplateDir);
    ClassPathTemplateLoader cpTemplateLoader = new ClassPathTemplateLoader((templatesDirPath));
    FileTemplateLoader fileTemplateLoader = new FileTemplateLoader(templatesDirPath);
    cpTemplateLoader.setSuffix(GeneratorConstants.TEMPLATES_SUFFIX);
    fileTemplateLoader.setSuffix(GeneratorConstants.TEMPLATES_SUFFIX);

    Handlebars handlebars = new Handlebars().with(cpTemplateLoader, fileTemplateLoader);
    handlebars.setStringParams(true);
    handlebars.registerHelpers(StringHelpers.class);
    handlebars.registerHelper("equals", (object, options) -> {
        Object param0 = options.param(0, null);

        if (param0 == null) {
            throw new IllegalArgumentException("found 'null', expected 'string'");
        }
        if (object != null && object.toString().equals(param0.toString())) {
                return options.fn(options.context);
        }

        return options.inverse();
    });

    return handlebars.compile(templateName);
}
 
Example 2
Source File: HandlebarsFactory.java    From commercetools-sunrise-java with Apache License 2.0 6 votes vote down vote up
static Handlebars create(final List<TemplateLoader> templateLoaders, final I18nResolver i18NResolver, final I18nIdentifierFactory i18nIdentifierFactory) {
    if (templateLoaders.isEmpty()) {
        throw new SunriseConfigurationException("Could not initialize Handlebars due to missing template loaders configuration", CONFIG_TEMPLATE_LOADERS);
    }
    logger.info("Provide Handlebars: template loaders [{}]]",
            templateLoaders.stream().map(TemplateLoader::getPrefix).collect(joining(", ")));
    final TemplateLoader[] loaders = templateLoaders.toArray(new TemplateLoader[templateLoaders.size()]);
    final Handlebars handlebars = new Handlebars()
            .with(loaders)
            .with(new HighConcurrencyTemplateCache())
            .infiniteLoops(true);
    handlebars.registerHelper("i18n", new HandlebarsI18nHelper(i18NResolver, i18nIdentifierFactory));
    handlebars.registerHelper("cms", new HandlebarsCmsHelper());
    handlebars.registerHelper("json", new HandlebarsJsonHelper<>());
    return handlebars;
}
 
Example 3
Source File: SingularityExecutorModule.java    From Singularity with Apache License 2.0 6 votes vote down vote up
@Provides
@Singleton
public Handlebars providesHandlebars() {
  SingularityRunnerBaseLogging.quietEagerLogging(); // handlebars emits DEBUG logs before logger is properly configured
  final Handlebars handlebars = new Handlebars();

  handlebars.registerHelper(BashEscapedHelper.NAME, new BashEscapedHelper());
  handlebars.registerHelper(ShellQuoteHelper.NAME, new ShellQuoteHelper());
  handlebars.registerHelper(IfPresentHelper.NAME, new IfPresentHelper());
  handlebars.registerHelper(
    IfHasNewLinesOrBackticksHelper.NAME,
    new IfHasNewLinesOrBackticksHelper()
  );
  handlebars.registerHelper(
    EscapeNewLinesAndQuotesHelper.NAME,
    new EscapeNewLinesAndQuotesHelper()
  );

  return handlebars;
}
 
Example 4
Source File: CustomHelperUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void whenHelperIsCreated_ThenCanRegister() throws IOException {
    Handlebars handlebars = new Handlebars(templateLoader);
    handlebars.registerHelper("isBusy", new Helper<Person>() {
        @Override
        public Object apply(Person context, Options options) throws IOException {
            String busyString = context.isBusy() ? "busy" : "available";
            return context.getName() + " - " + busyString;
        }
    });
    Template template = handlebars.compile("person");
    Person person = getPerson("Baeldung");

    String templateString = template.apply(person);

    assertThat(templateString).isEqualTo("Baeldung - busy");
}
 
Example 5
Source File: BaragonAgentServiceModule.java    From Baragon with Apache License 2.0 6 votes vote down vote up
@Provides
@Singleton
public Handlebars providesHandlebars(BaragonAgentConfiguration config, BaragonAgentMetadata agentMetadata, UpstreamResolver resolver) {
  final Handlebars handlebars = new Handlebars();

  handlebars.registerHelper(FormatTimestampHelper.NAME, new FormatTimestampHelper(config.getDefaultDateFormat()));
  handlebars.registerHelper(FirstOfHelper.NAME, new FirstOfHelper(""));
  handlebars.registerHelper(CurrentRackIsPresentHelper.NAME, new CurrentRackIsPresentHelper(agentMetadata.getEc2().getAvailabilityZone()));
  handlebars.registerHelper(ResolveHostnameHelper.NAME, new ResolveHostnameHelper(resolver));
  handlebars.registerHelpers(new PreferSameRackWeightingHelper(config, agentMetadata));
  handlebars.registerHelpers(IfEqualHelperSource.class);
  handlebars.registerHelpers(IfContainedInHelperSource.class);
  handlebars.registerHelper(ToNginxVarHelper.NAME, new ToNginxVarHelper());

  return handlebars;
}
 
Example 6
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 7
Source File: HandlebarsHelper.java    From spring-cloud-release-tools with Apache License 2.0 5 votes vote down vote up
public static Template template(String templateSubFolder, String templateName) {
	try {
		Handlebars handlebars = new Handlebars(
				new ClassPathTemplateLoader("/templates/" + templateSubFolder));
		handlebars.registerHelper("replace", StringHelpers.replace);
		handlebars.registerHelper("capitalizeFirst", StringHelpers.capitalizeFirst);
		return handlebars.compile(templateName);
	}
	catch (IOException e) {
		throw new IllegalStateException(e);
	}
}
 
Example 8
Source File: TemplateEngine.java    From bonita-ui-designer with GNU General Public License v2.0 5 votes vote down vote up
public TemplateEngine(String template) {
    SimpleFilterProvider simpleFilterProvider = new SimpleFilterProvider();
    simpleFilterProvider.setFailOnUnknownId(false);
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setFilters(simpleFilterProvider);

    handlebars = new Handlebars(new ClassPathTemplateLoader("/", ""));
    handlebars.registerHelper("json", new Jackson2Helper(objectMapper));
    handlebars.registerHelper("join", StringHelpers.join);
    handlebars.registerHelper("ifequal", IfEqualHelper.INSTANCE);
    handlebars.prettyPrint(true);

    location = "templates/" + template;
}
 
Example 9
Source File: VaadinConnectTsGenerator.java    From flow with Apache License 2.0 5 votes vote down vote up
@Override
public void addHandlebarHelpers(Handlebars handlebars) {
    super.addHandlebarHelpers(handlebars);
    handlebars.registerHelper("multiplelines", getMultipleLinesHelper());
    handlebars.registerHelper("getClassNameFromImports",
            getClassNameFromImportsHelper());
    handlebars.registerHelper("getModelType", getModelTypeHelper());
    handlebars.registerHelper("getModelConstructor",
            getModelConstructorHelper());
}
 
Example 10
Source File: PASystemImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
private Handlebars loadHandleBars(final I18n i18n) {
    Handlebars handlebars = new Handlebars()
            .with(cache);

    handlebars.registerHelper("t", new Helper<Object>() {
        @Override
        public CharSequence apply(final Object context, final Options options) {
            String key = options.param(0);
            return i18n.t(key);
        }
    });

    return handlebars;
}
 
Example 11
Source File: Xsd2JaxbGenerator.java    From legstar-core2 with GNU Affero General Public License v3.0 5 votes vote down vote up
public Xsd2JaxbGenerator() {
    Handlebars handlebars = new Handlebars();
    handlebars.registerHelper("capFirst", StringHelpers.capitalize);
    handlebars.registerHelper("each",
            new com.legstar.jaxb.generator.EachHelper());
    hbtJaxbWrapperFactoryClass = loadTemplate(handlebars,
            JAXB_WRAPPER_FACTORY_CLASS_TEMPLATE_NAME);
    hbtJaxbConverterClass = loadTemplate(handlebars,
            JAXB_CONVERTER_CLASS_TEMPLATE_NAME);
    modelBuilder = new Xsd2CobolTypesModelBuilder();
}
 
Example 12
Source File: PASystemImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
private Handlebars loadHandleBars(final I18n i18n) {
    Handlebars handlebars = new Handlebars()
            .with(cache);

    handlebars.registerHelper("t", new Helper<Object>() {
        @Override
        public CharSequence apply(final Object context, final Options options) {
            String key = options.param(0);
            return i18n.t(key);
        }
    });

    return handlebars;
}
 
Example 13
Source File: HandlebarsHelper.java    From spring-cloud-release with Apache License 2.0 5 votes vote down vote up
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 14
Source File: HandlebarsHelper.java    From dew with Apache License 2.0 4 votes vote down vote up
public static void registerFormatClassName(Handlebars handlebars) {
    handlebars.registerHelper("formatClassName",
            (Helper<String>) (s, options) -> NameHelper.formatClassName(s));
}
 
Example 15
Source File: HandlebarsHelper.java    From dew with Apache License 2.0 4 votes vote down vote up
public static void registerFormatPackage(Handlebars handlebars) {
    handlebars.registerHelper("formatPackage",
            (Helper<String>) (s, options) -> NameHelper.formatPackage(s));
}