Java Code Examples for com.github.jknack.handlebars.Options

The following examples show how to use com.github.jknack.handlebars.Options. These examples are extracted from open source projects. 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 Project: arcusplatform   Author: arcus-smart-home   File: PluralizeHelper.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public CharSequence apply(Number context, Options options) throws IOException {
   if(context == null) {
     throw new IllegalArgumentException("a number must be provided as the first argument");
   }
   if(options.params == null || options.params.length < 2) {
      throw new IllegalArgumentException("two strings must be provided as the second and third arguments");
   }

   String singular = String.valueOf(options.params[0]);
   String plural = String.valueOf(options.params[1]);

   // 0 is plural in English
   if(context.intValue() == 1) {
      return singular;
   }
   return plural;
}
 
Example #2
Source Project: bootstraped-multi-test-results-report   Author: web-innovate   File: Helpers.java    License: MIT License 6 votes vote down vote up
private Helper<Long> dateHelper() {
    return new Helper<Long>() {
        public CharSequence apply(Long arg0, Options arg1) throws IOException {
            PeriodFormatter formatter = new PeriodFormatterBuilder()
                .appendDays()
                .appendSuffix(" d : ")
                .appendHours()
                .appendSuffix(" h : ")
                .appendMinutes()
                .appendSuffix(" m : ")
                .appendSeconds()
                .appendSuffix(" s : ")
                .appendMillis()
                .appendSuffix(" ms")
                .toFormatter();
            return formatter.print(new Period((arg0 * 1) / 1000000));
        }
    };
}
 
Example #3
Source Project: legstar-core2   Author: legsem   File: EachHelper.java    License: 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 #4
Source Project: cloudbreak   Author: hortonworks   File: FormatJoinHelper.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Object apply(Collection<?> context, Options options) {
    if (context == null || context.isEmpty()) {
        return "";
    }

    String separator = options.hash("sep", ",");
    String format = options.hash("format", null);

    Function<Object, String> formatter = format != null
            ? each -> String.format(format, each)
            : Object::toString;

    return context.stream()
            .map(formatter)
            .collect(joining(separator));
}
 
Example #5
Source Project: cloudbreak   Author: hortonworks   File: ComponentPresentedHelper.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Object apply(Set<String> context, Options options)
        throws IOException {
    String first = options.param(0, null);

    Validate.notNull(first, "found 'null', expected 'first'");
    if (context == null) {
        context = new HashSet<>();
    }

    Buffer buffer = options.buffer();
    if (!context.contains(first)) {
        buffer.append(options.inverse());
    } else {
        buffer.append(options.fn());
    }
    return buffer;
}
 
Example #6
Source Project: Singularity   Author: HubSpot   File: BashEscapedHelper.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public CharSequence apply(Object context, Options options) throws IOException {
  if (context == null) {
    return "\"\"";
  }

  final StringBuilder sb = new StringBuilder();

  sb.append('"');

  for (char c : context.toString().toCharArray()) {
    if (c == '\\' || c == '\"' || c == '`') {
      sb.append('\\');
      sb.append(c);
    } else if (c == '!') {
      sb.append("\"'!'\"");
    } else {
      sb.append(c);
    }
  }

  sb.append('"');

  return sb.toString();
}
 
Example #7
Source Project: Singularity   Author: HubSpot   File: ShellQuoteHelper.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public CharSequence apply(Object context, Options options) throws IOException {
  if (context == null) {
    return "''";
  }

  final StringBuilder sb = new StringBuilder();

  sb.append("'");

  for (char c : context.toString().toCharArray()) {
    if (c == '\'') {
      sb.append("'\"'\"'");
    } else if (c == '\n') {
      sb.append('\\');
      sb.append('n');
    } else {
      sb.append(c);
    }
  }

  sb.append("'");

  return sb.toString();
}
 
Example #8
Source Project: Singularity   Author: HubSpot   File: EscapeNewLinesAndQuotesHelper.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public CharSequence apply(Object context, Options options) throws IOException {
  if (context == null) {
    return "\"\"";
  }

  final StringBuilder sb = new StringBuilder();

  sb.append('"');

  for (char c : context.toString().toCharArray()) {
    if (c == '\n') {
      sb.append('\\');
      sb.append('n');
    } else if (c == '"') {
      sb.append('\\');
      sb.append('"');
    } else {
      sb.append(c);
    }
  }

  sb.append('"');

  return sb.toString();
}
 
Example #9
Source Project: tutorials   Author: eugenp   File: CustomHelperUnitTest.java    License: 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 #10
Source Project: Baragon   Author: HubSpot   File: FormatTimestampHelper.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public CharSequence apply(Number context, Options options) throws IOException {
  String dateFormatString;
  try {
    dateFormatString = options.param(0, defaultFormatString);
  } catch (ClassCastException cce) {  // phorce.
    LOG.warn(String.format("Date format %s isn't subclass of String, using default: %s", options.param(0), defaultFormatString));
    dateFormatString = defaultFormatString;
  }

  final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatString);

  final Calendar cal = Calendar.getInstance();
  cal.setTimeInMillis(context.longValue());

  return simpleDateFormat.format(cal.getTime());
}
 
Example #11
Source Project: Baragon   Author: HubSpot   File: CurrentRackIsPresentHelper.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public CharSequence apply(Collection<UpstreamInfo> upstreams, Options options) throws IOException {
  if (!currentRackId.isPresent()) {
    return options.fn();
  }

  if (upstreams == null) {
    return options.inverse();
  }

  for (UpstreamInfo upstreamInfo : upstreams) {
    if (upstreamInfo.getRackId().isPresent() && upstreamInfo.getRackId().get().toLowerCase().equals(currentRackId.get().toLowerCase())) {
      return options.fn();
    }
  }
  return options.inverse();
}
 
Example #12
Source Project: Baragon   Author: HubSpot   File: FirstOfHelper.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public CharSequence apply(Object context, Options options) throws IOException {
  // handle null
  if (context == null) {
    return options.param(0, fallback).toString();
  }

  // handle optional
  if (context instanceof Optional) {
    final Optional<Object> contextOptional = (Optional<Object>) context;
    return contextOptional.or(options.param(0, fallback)).toString();
  }

  // handle empty string
  if (context instanceof String) {
    final String contextString = (String) context;

    return !Strings.isNullOrEmpty(contextString) ? contextString : options.param(0, fallback).toString();
  }

  // otherwise just return context
  return context.toString();
}
 
Example #13
Source Project: arcusplatform   Author: arcus-smart-home   File: EnumHelper.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public CharSequence apply(String context, Options options) throws IOException {
 if (StringUtils.isEmpty(context)) {
 	return "";
 }
 String value = options.hash(context);
 return value != null ? value : context.toLowerCase().replace('_', ' ');
}
 
Example #14
Source Project: arcusplatform   Author: arcus-smart-home   File: HandlebarsHelpersSource.java    License: Apache License 2.0 5 votes vote down vote up
public static CharSequence section(String sectionName, Options options) throws IOException {
	StringBuilder sb = new StringBuilder();
	sb.append(String.format("---%s---", sectionName))
	.append(options.fn())
	.append(String.format("!--%s---", sectionName));
	return sb.toString();
}
 
Example #15
Source Project: arcusplatform   Author: arcus-smart-home   File: HandlebarsHelpersSource.java    License: Apache License 2.0 5 votes vote down vote up
public static CharSequence celsiusToFahrenheit(String temperatureInC, Options options) throws IOException {
	String formattedValue = "";
	if(StringUtils.isNoneBlank(temperatureInC)) {
		double temperatureInCValue = Double.valueOf(temperatureInC);
		formattedValue = BigDecimal.valueOf(UnitConversion.tempCtoF(temperatureInCValue)).setScale(0, BigDecimal.ROUND_HALF_DOWN).toString();			 
	}
	return formattedValue;
}
 
Example #16
Source Project: arcusplatform   Author: arcus-smart-home   File: IfEqualHelper.java    License: 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 #17
Source Project: arcusplatform   Author: arcus-smart-home   File: HandleBarsTemplateServiceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testInjectCustomHelper() {
	HashMap<String, Helper<? extends Object>> helpers = new HashMap<String, Helper<? extends Object>>();
	helpers.put("testhelper",(Object a, Options o)->{return "hello";});
	service.registerHelpers(helpers);
	String template = service.render("test-customhelper", context);
	assertEquals("hello", template);		
}
 
Example #18
Source Project: zerocode   Author: authorjapps   File: HandlebarsLocalDateHelper.java    License: Apache License 2.0 5 votes vote down vote up
public Object apply(Object context, Options options) {
    String offset = options.hash("offset", null);
    Date date = new Date();
    if (offset != null) {
        date = (new DateOffset(offset)).shift(date);
    }
    return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime().format(DateTimeFormatter.ISO_DATE_TIME);
}
 
Example #19
Source Project: bootstraped-multi-test-results-report   Author: web-innovate   File: Helpers.java    License: MIT License 5 votes vote down vote up
private Helper<String> embeddingHelper() {
    return new Helper<String>() {
        @Override
        public CharSequence apply(String arg0, Options arg1) throws IOException {
            String toReturn;
            String id = UUID.randomUUID().toString();
            int index = arg1.param(1);
            if (arg1.param(0).toString().contains("image")) {
                toReturn =
                    "<button 'type='button'"
                        + "class='btn btn-primary'"
                        + "data-toggle='modal' "
                        + "data-target='#" + id + "'>"
                        + "  Screenshot " + ++index + ""
                        + "</button>";
                toReturn +=
                    "<div id='" + id + "'"
                        + "class='modal fade'"
                        + "tabindex='-1'"
                        + "role='dialog'"
                        + "aria-labelledby='myModalLabel'"
                        + "aria-hidden='true'>"
                        + "  <div style='width:90%;height:90%;'"
                        + "  class='modal-dialog'>"
                        + "    <div class='modal-content'>"
                        + "      <div class='modal-body'>"
                        + "        <img "
                        + "        src='data:image/png;base64," + arg0 + "'"
                        + "        class='img-responsive'>"
                        + "      </div>"
                        + "    </div>"
                        + "  </div>"
                        + "</div>";
            } else {
                toReturn = "<pre>" + arg0 + "</pre>";
            }
            return toReturn;
        }
    };
}
 
Example #20
Source Project: bootstraped-multi-test-results-report   Author: web-innovate   File: Helpers.java    License: MIT License 5 votes vote down vote up
private Helper<String> resultColorHelper() {
    return new Helper<String>() {
        @Override
        public CharSequence apply(String arg0, Options arg1) throws IOException {
            return checkState(
                arg0.toLowerCase(),
                Constants.INFO,
                Constants.SUCCESS,
                Constants.DANGER,
                Constants.WARNING);
        }
    };
}
 
Example #21
Source Project: bootstraped-multi-test-results-report   Author: web-innovate   File: Helpers.java    License: MIT License 5 votes vote down vote up
private Helper<String> resolveTitleHelper() {
    return new Helper<String>() {
        @Override
        public CharSequence apply(String arg0, Options arg1) throws IOException {
            return checkState(
                arg0.toLowerCase(),
                Constants.THIS_STEP_HAS_BEEN_SKIPPED,
                Constants.THIS_STEP_HAS_PASSED,
                Constants.THIS_STEP_HAS_FAILED,
                Constants.THIS_STEP_HAS_NOT_BEEN_DEFINED);
        }
    };
}
 
Example #22
Source Project: bootstraped-multi-test-results-report   Author: web-innovate   File: Helpers.java    License: MIT License 5 votes vote down vote up
private Helper<String> isCollapsedHelper() {
    return new Helper<String>() {
        @Override
        public CharSequence apply(String arg0, Options arg1) throws IOException {
            return checkState(
                arg0.toLowerCase(),
                Constants.COLLAPSE_IN,
                Constants.COLLAPSE,
                Constants.COLLAPSE_IN,
                Constants.COLLAPSE_IN);
        }
    };
}
 
Example #23
Source Project: bootstraped-multi-test-results-report   Author: web-innovate   File: Helpers.java    License: MIT License 5 votes vote down vote up
private Helper<Object> nowHelper() {
    return new Helper<Object>() {
        @Override
        public CharSequence apply(Object context, Options options) throws IOException {
            Calendar cal = Calendar.getInstance();
            Date date = cal.getTime();
            String now = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").format(date);
            TimeZone tz = cal.getTimeZone();
            return now + " " + tz.getID();
        }
    };
}
 
Example #24
Source Project: bootstraped-multi-test-results-report   Author: web-innovate   File: Helpers.java    License: MIT License 5 votes vote down vote up
private Helper<List<StepRow>> doTableHelperForStep() {
    return new Helper<List<StepRow>>() {
        @Override
        public CharSequence apply(List<StepRow> rows, Options arg1) throws IOException {
            String tableContent = "<table  class='table table-condensed table-hover'>";
            int indexRow = 0;
            for (StepRow row : rows) {
                indexRow++;
                if (indexRow == 1) {
                    tableContent += "<thead><tr>";
                } else if (indexRow == 2) {
                    tableContent += "<tbody><tr>";
                } else {
                    tableContent += "<tr>";
                }
                for (String cell : row.getCells()) {
                    if (indexRow == 1) {
                        tableContent += "<th>" + cell + "</th>";
                    } else {
                        tableContent += "<td>" + cell + "</td>";
                    }
                }
                if (indexRow == 1) {
                    tableContent += "</tr></thead>";
                } else {
                    tableContent += "</tr>";
                }
            }
            tableContent += "</tbody></table>";
            return tableContent;
        }
    };
}
 
Example #25
Source Project: bootstraped-multi-test-results-report   Author: web-innovate   File: Helpers.java    License: MIT License 5 votes vote down vote up
private Helper<List<Row>> doTableHelper() {
    return new Helper<List<Row>>() {
        @Override
        public CharSequence apply(List<Row> rows, Options arg1) throws IOException {
            String tableContent = "<table  class='table table-condensed table-hover'>";
            int indexRow = 0;
            for (Row row : rows) {
                indexRow++;
                if (indexRow == 1) {
                    tableContent += "<thead><tr>";
                } else if (indexRow == 2) {
                    tableContent += "<tbody><tr>";
                } else {
                    tableContent += "<tr>";
                }
                for (String cell : row.getCells()) {
                    if (indexRow == 1) {
                        tableContent += "<th>" + cell + "</th>";
                    } else {
                        tableContent += "<td>" + cell + "</td>";
                    }
                }
                if (indexRow == 1) {
                    tableContent += "</tr></thead>";
                } else {
                    tableContent += "</tr>";
                }
            }
            tableContent += "</tbody></table>";
            return tableContent;
        }
    };
}
 
Example #26
Source Project: bonita-ui-designer   Author: bonitasoft   File: IfEqualHelper.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public CharSequence apply(final Object context, final Options options)
        throws IOException {
    if (options.hash.get("value").equals(context.toString())) {
        return options.fn();
    } else {
        return options.inverse();
    }
}
 
Example #27
Source Project: flow   Author: vaadin   File: VaadinConnectTsGenerator.java    License: 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 #28
Source Project: sakai   Author: sakaiproject   File: PASystemImpl.java    License: 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 #29
Source Project: template-benchmark   Author: mbosecke   File: Handlebars.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Setup
public void setup() throws IOException {
  template = new com.github.jknack.handlebars.Handlebars(new ClassPathTemplateLoader("/", ".html"))
          .registerHelper("minus", new Helper<Stock>() {
            @Override
            public CharSequence apply(final Stock stock, final Options options)
                throws IOException {
              return stock.getChange() < 0 ? new SafeString("class=\"minus\"") : null;
            }
          }).compile("templates/stocks.hbs");
  this.context = getContext();
}
 
Example #30
Source Project: legstar-core2   Author: legsem   File: EachHelper.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
@SuppressWarnings({"rawtypes", "unchecked" })
public CharSequence apply(final Object context, final Options options)
    throws IOException {
  if (context == null) {
    return StringUtils.EMPTY;
  }
  if (context instanceof Iterable) {
    return iterableContext((Iterable) context, options);
  }
  return hashContext(context, options);
}