com.github.jknack.handlebars.Context Java Examples

The following examples show how to use com.github.jknack.handlebars.Context. 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: EachHelper.java    From legstar-core2 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
* Iterate over a hash like object.
*
* @param context The context object.
* @param options The helper options.
* @return The string output.
* @throws IOException If something goes wrong.
*/
 private CharSequence hashContext(final Object context, final Options options)
         throws IOException {
     Set < Entry < String, Object >> propertySet = options
             .propertySet(context);
     StringBuilder buffer = new StringBuilder();
     Context parent = options.context;
     boolean first = true;
     for (Entry < String, Object > entry : propertySet) {
         Context current = Context.newBuilder(parent, entry.getValue())
                 .combine("@key", entry.getKey())
                 .combine("@first", first ? "first" : "").build();
         buffer.append(options.fn(current));
         current.destroy();
         first = false;
     }
     return buffer.toString();
 }
 
Example #2
Source File: IfEqualHelper.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public CharSequence apply(String context, Options options) throws IOException {
	if (options.params.length != 1 || !(options.params[0] instanceof String)) {
		throw new IllegalArgumentException(
				"#if_equal requires one and only one String as an argument to compare against.\nShould be of the form:\n{{#if_equal someVar \"MYSTRING\"}}The value of someVar is MYSTRING{{else}}The value of someVar is not MYSTRING{/if_equal}}");
	}

	String match = (String) options.params[0];

	if (context == null || !context.equals(match)) {
		return options.inverse(Context.newContext(options.context, context));
	}

	return options.fn(Context.newContext(options.context, context));
}
 
Example #3
Source File: LbConfigGenerator.java    From Baragon with Apache License 2.0 5 votes vote down vote up
public Collection<BaragonConfigFile> generateConfigsForProject(ServiceContext snapshot) throws MissingTemplateException {
  final Collection<BaragonConfigFile> files = Lists.newArrayList();
  String templateName = snapshot.getService().getTemplateName().or(BaragonAgentServiceModule.DEFAULT_TEMPLATE_NAME);

  List<LbConfigTemplate> matchingTemplates = templates.get(templateName);

  if (templates.get(templateName) != null) {
    for (LbConfigTemplate template : matchingTemplates) {
      final List<String> filenames = getFilenames(template, snapshot.getService());

      final StringWriter sw = new StringWriter();
      final Context context = Context.newBuilder(snapshot).combine("agentProperties", agentMetadata).build();
      try {
        template.getTemplate().apply(context, sw);
      } catch (Exception e) {
        throw Throwables.propagate(e);
      }

      for (String filename : filenames) {
        files.add(new BaragonConfigFile(String.format("%s/%s", loadBalancerConfiguration.getRootPath(), filename), sw.toString()));
      }
    }
  } else {
    throw new MissingTemplateException(String.format("MissingTemplateException : Template %s could not be found", templateName));
  }

  return files;
}
 
Example #4
Source File: TemplateExpressionEvaluator.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public Object evaluate(Entity entity) {
  initTemplate();

  Map<String, Object> tagValues = getTemplateTagValue(entity);

  try {
    return template.apply(Context.newContext(tagValues));
  } catch (IOException e) {
    throw new TemplateExpressionException(attribute, e);
  }
}
 
Example #5
Source File: HandlebarsTemplateEngineImpl.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Override
public void render(Map<String, Object> context, String templateFile, Handler<AsyncResult<Buffer>> handler) {
  try {
    String src = adjustLocation(templateFile);
    TemplateHolder<Template> template = getTemplate(src);

    if (template == null) {
      // either it's not cache or cache is disabled
      int idx = src.lastIndexOf('/');
      String prefix = "";
      String basename = src;
      if (idx != -1) {
        prefix = src.substring(0, idx);
        basename = src.substring(idx + 1);
      }
      synchronized (this) {
        loader.setPrefix(prefix);
        template = new TemplateHolder<>(handlebars.compile(basename), prefix);
      }
      putTemplate(src, template);
    }

    Context engineContext = Context.newBuilder(context).resolver(getResolvers()).build();
    handler.handle(Future.succeededFuture(Buffer.buffer(template.template().apply(engineContext))));
  } catch (Exception ex) {
    handler.handle(Future.failedFuture(ex));
  }
}
 
Example #6
Source File: AllHelperTest.java    From roboconf-platform with Apache License 2.0 5 votes vote down vote up
@Test
public void testUnsupportedContext_nullContext() throws Exception {

	Context ctx = Context.newContext( null );
	Handlebars handlebars = Mockito.mock( Handlebars.class );
	Template tpl = Mockito.mock(  Template.class  );
	Options opts = new Options(
			handlebars, "helper", TagType.SECTION, ctx, tpl, tpl,
			new Object[ 0 ],
			new HashMap<String,Object>( 0 ));

	AllHelper helper = new AllHelper();
	Assert.assertEquals( "", helper.apply( null, opts ));
}
 
Example #7
Source File: AllHelperTest.java    From roboconf-platform with Apache License 2.0 5 votes vote down vote up
@Test
public void testUnsupportedContext_unknownType() throws Exception {

	Context ctx = Context.newContext( new Object());
	Handlebars handlebars = Mockito.mock( Handlebars.class );
	Template tpl = Mockito.mock(  Template.class  );
	Options opts = new Options(
			handlebars, "helper", TagType.SECTION, ctx, tpl, tpl,
			new Object[ 0 ],
			new HashMap<String,Object>( 0 ));

	AllHelper helper = new AllHelper();
	Assert.assertEquals( "", helper.apply( null, opts ));
}
 
Example #8
Source File: AllHelper.java    From roboconf-platform with Apache License 2.0 5 votes vote down vote up
/**
 * Same as above, but with type-safe arguments.
 *
 * @param instances the instances to which this helper is applied.
 * @param options   the options of this helper invocation.
 * @return a string result.
 * @throws IOException if a template cannot be loaded.
 */
private String safeApply( Collection<InstanceContextBean> instances, Options options, String componentPath )
throws IOException {

	// Parse the filter.
	String installerName = (String) options.hash.get( "installer" );
	final InstanceFilter filter = InstanceFilter.createFilter( componentPath, installerName );

	// Apply the filter.
	final Collection<InstanceContextBean> selectedInstances = filter.apply( instances );

	// Apply the content template of the helper to each selected instance.
	final StringBuilder buffer = new StringBuilder();
	final Context parent = options.context;
	int index = 0;
	final int last = selectedInstances.size() - 1;

	for( final InstanceContextBean instance : selectedInstances ) {
		final Context current = Context.newBuilder( parent, instance )
				.combine( "@index", index )
				.combine( "@first", index == 0 ? "first" : "" )
				.combine( "@last", index == last ? "last" : "" )
				.combine( "@odd", index % 2 == 0 ? "" : "odd" )
				.combine( "@even", index % 2 == 0 ? "even" : "" )
				.build();

		index++;
		buffer.append( options.fn( current ));
	}

	return buffer.toString();
}
 
Example #9
Source File: EachHelper.java    From legstar-core2 with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Iterate over an iterable object.
 *
 * @param context The context object.
 * @param options The helper options.
 * @return The string output.
 * @throws IOException If something goes wrong.
 */
private CharSequence iterableContext(final Iterable<Object> context, final Options options)
    throws IOException {
  StringBuilder buffer = new StringBuilder();
  if (options.isFalsy(context)) {
    buffer.append(options.inverse());
  } else {
    Iterator<Object> iterator = context.iterator();
    int index = -1;
    Context parent = options.context;
    while (iterator.hasNext()) {
      index += 1;
      Object element = iterator.next();
      boolean first = index == 0;
      boolean even = index % 2 == 0;
      boolean last = !iterator.hasNext();
      Context current = Context.newBuilder(parent, element)
          .combine("@index", index)
          .combine("@first", first ? "first" : "")
          .combine("@last", last ? "last" : "")
          .combine("@odd", even ? "" : "odd")
          .combine("@even", even ? "even" : "")
          .build();
      buffer.append(options.fn(current));
      current.destroy();
    }
  }
  return buffer.toString();
}
 
Example #10
Source File: HandlebarsI18nHelper.java    From commercetools-sunrise-java with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private static List<Locale> getLocalesFromContext(final Context context) {
    final Object languageTagsAsObject = context.get(LANGUAGE_TAGS_IN_CONTEXT_KEY);
    if (languageTagsAsObject instanceof List) {
        final List<String> locales = (List<String>) languageTagsAsObject;
        return locales.stream()
                .map(Locale::forLanguageTag)
                .collect(toList());
    } else {
        return emptyList();
    }
}
 
Example #11
Source File: HandlebarsCmsHelper.java    From commercetools-sunrise-java with Apache License 2.0 5 votes vote down vote up
private static Optional<CmsPage> getCmsPageFromContext(final Context context) {
    final Object cmsPageAsObject = context.get(CMS_PAGE_IN_CONTEXT_KEY);
    if (cmsPageAsObject instanceof CmsPage) {
        final CmsPage cmsPage = (CmsPage) cmsPageAsObject;
        return Optional.of(cmsPage);
    } else {
        return Optional.empty();
    }
}
 
Example #12
Source File: TemplateEngine.java    From bonita-ui-designer with GNU General Public License v2.0 5 votes vote down vote up
public String build(Object context) throws GenerationException {
    try {
        return handlebars
                .compile(location)
                .apply(Context.newBuilder(context).combine(model).build());
    } catch (IOException e) {
        throw new GenerationException("Error applying context to template <" + location + ">", e);
    }
}
 
Example #13
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 #14
Source File: ObjCProcessor.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
protected CharSequence typeOfEnum(Context parent) {
 Context topParent = parent.parent();
    while (topParent.parent() != null) {
        topParent = topParent.parent();
    }
    String name = StringUtils.capitalize(((Definition)topParent.model()).getName());
    return name + StringUtils.capitalize(((Definition)parent.model()).getName());
}
 
Example #15
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 #16
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 #17
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 #18
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 #19
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 #20
Source File: VaadinConnectTsGenerator.java    From flow with Apache License 2.0 5 votes vote down vote up
private Helper<String> getMultipleLinesHelper() {
    return (context, options) -> {
        Options.Buffer buffer = options.buffer();
        String[] lines = context.split("\n");
        Context parent = options.context;
        Template fn = options.fn;
        for (String line : lines) {
            buffer.append(options.apply(fn, parent.combine("@line", line)));
        }
        return buffer;
    };
}
 
Example #21
Source File: HandlebarsContextFactory.java    From commercetools-sunrise-java with Apache License 2.0 4 votes vote down vote up
protected final Context.Builder contextBuilderWithValueResolvers(final Context.Builder contextBuilder, final TemplateContext templateContext) {
    final List<ValueResolver> valueResolvers = valueResolversInContext(templateContext);
    return contextBuilder.resolver(valueResolvers.toArray(new ValueResolver[valueResolvers.size()]));
}
 
Example #22
Source File: HandlebarsContextFactory.java    From commercetools-sunrise-java with Apache License 2.0 4 votes vote down vote up
protected final Context contextWithLocale(final Context context, final TemplateContext templateContext) {
    return context.data(LANGUAGE_TAGS_IN_CONTEXT_KEY, localesInContext(templateContext));
}
 
Example #23
Source File: HandlebarsContextFactory.java    From commercetools-sunrise-java with Apache License 2.0 4 votes vote down vote up
protected final Context contextWithCmsPage(final Context context, final TemplateContext templateContext) {
    return cmsPageInContext(templateContext)
            .map(cmsPage -> context.data(CMS_PAGE_IN_CONTEXT_KEY, cmsPage))
            .orElse(context);
}
 
Example #24
Source File: HandlebarsContextFactory.java    From commercetools-sunrise-java with Apache License 2.0 4 votes vote down vote up
protected final Context createContext(final Context.Builder contextBuilder, final TemplateContext templateContext) {
    final Context contextWithLocale = contextWithLocale(contextBuilder.build(), templateContext);
    return contextWithCmsPage(contextWithLocale, templateContext);
}
 
Example #25
Source File: HandlebarsContextFactory.java    From commercetools-sunrise-java with Apache License 2.0 4 votes vote down vote up
protected final Context.Builder createContextBuilder(final TemplateContext templateContext) {
    final Context.Builder contextBuilder = Context.newBuilder(templateContext.pageData());
    return contextBuilderWithValueResolvers(contextBuilder, templateContext);
}
 
Example #26
Source File: ViewHelper.java    From fess with Apache License 2.0 4 votes vote down vote up
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;
}
 
Example #27
Source File: HandlebarsContextFactory.java    From commercetools-sunrise-java with Apache License 2.0 4 votes vote down vote up
public Context create(final Handlebars handlebars, final String templateName, final TemplateContext templateContext) {
    final Context.Builder contextBuilder = createContextBuilder(templateContext);
    return createContext(contextBuilder, templateContext);
}
 
Example #28
Source File: CodeGenerator.java    From product-microgateway with Apache License 2.0 3 votes vote down vote up
/**
 * Retrieve generated source content as a String value.
 *
 * @param endpoints    context to be used by template engine
 * @param templateName name of the template to be used for this code generation
 * @return String with populated template
 * @throws IOException when template population fails
 */
private String getContent(Object endpoints, String templateName) throws IOException {
    Template template = CodegenUtils.compileTemplate(GeneratorConstants.DEFAULT_TEMPLATE_DIR, templateName);
    Context context = Context.newBuilder(endpoints)
            .resolver(MapValueResolver.INSTANCE, JavaBeanValueResolver.INSTANCE, FieldValueResolver.INSTANCE)
            .build();
    return template.apply(context);
}