org.trimou.engine.MustacheEngine Java Examples
The following examples show how to use
org.trimou.engine.MustacheEngine.
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: ValueConverterTest.java From trimou with Apache License 2.0 | 6 votes |
@Test public void testInvalidValueConverter() { MustacheEngine engine = MustacheEngineBuilder.newBuilder() .addValueConverter(new ValueConverter() { @Override public String convert(Object from) { return from.toString().toUpperCase(); } @Override public boolean isValid() { return false; } }).build(); assertEquals("Foo", engine.compileMustache("value_converter_invalid", "{{this}}") .render("Foo")); }
Example #2
Source File: OptionsTest.java From trimou with Apache License 2.0 | 6 votes |
@Test public void testHash() { MustacheEngine engine = MustacheEngineBuilder.newBuilder() .registerHelper("test", new AbstractHelper() { @Override public void execute(Options options) { final Map<String, Object> hash = options.getHash(); assertEquals(3, hash.size()); assertEquals("1", hash.get("first")); assertEquals(10, hash.get("second")); assertNull(hash.get("third")); ExceptionAssert .expect(UnsupportedOperationException.class) .check(() -> hash.remove("first")); } }).build(); engine.compileMustache("helper_params", "{{test first=\"1\" second=this.age third=nonexisting}}") .render(new Hammer()); }
Example #3
Source File: EmbedHelperTest.java From trimou with Apache License 2.0 | 6 votes |
@Test public void testEmbeddedHelper() { MustacheEngine engine = MustacheEngineBuilder .newBuilder() .registerHelpers(HelpersBuilder.empty().addEmbed().build()) .addTemplateLocator( new MapTemplateLocator(ImmutableMap.of("template", "Hello!"))).build(); assertEquals( "<script id=\"template\" type=\"text/template\">\nHello!\n</script>", engine.compileMustache("embed_helper01", "{{embed this}}") .render("template")); assertEquals( "<script id=\"template\" type=\"text/template\">\nHello!\n</script>", engine.compileMustache("embed_helper01", "{{embed 'temp' this}}") .render("late")); }
Example #4
Source File: OptionsTest.java From trimou with Apache License 2.0 | 6 votes |
@Test public void testGetAppendable() { MustacheEngine engine = MustacheEngineBuilder.newBuilder() .registerHelper("test", new AbstractHelper() { @Override public void execute(Options options) { try { options.getAppendable() .append(options.peek().toString()); } catch (IOException e) { throw new RuntimeException(e); } } }).build(); assertEquals("HELLO", engine.compileMustache("helper_getappendable", "{{test}}") .render("HELLO")); }
Example #5
Source File: SwitchHelperTest.java From trimou with Apache License 2.0 | 6 votes |
@Test public void testSwitchHelperValidation() { final MustacheEngine engine = MustacheEngineBuilder.newBuilder() .registerHelpers(HelpersBuilder.empty().addSwitch().build()) .build(); MustacheExceptionAssert .expect(MustacheProblem.COMPILE_HELPER_VALIDATION_FAILURE) .check(() -> engine.compileMustache( "switch_helper_validation01", "{{switch}}")) .check(() -> engine.compileMustache( "switch_helper_validation02", "{{#switch}}{{case \"true\"}}{{/switch}}")) .check(() -> engine.compileMustache( "switch_helper_validation03", "{{#switch}}{{#case \"true\"}}{{/case}}{{default \"foo\"}}{{/switch}}")); }
Example #6
Source File: ExtendSegmentTest.java From trimou with Apache License 2.0 | 6 votes |
@Test public void testExtendNotFound() { MustacheEngine engine = MustacheEngineBuilder.newBuilder().build(); try { engine.compileMustache("extend_not_found", "Hello,\nan attempt to extend \n\n {{<neverexisted}}{{/neverexisted}}") .render(null); fail("Template to extend does not exist!"); } catch (MustacheException e) { if (!e.getCode().equals(MustacheProblem.RENDER_INVALID_EXTEND_KEY)) { fail("Invalid problem"); } System.out.println(e.getMessage()); } }
Example #7
Source File: OptionsTest.java From trimou with Apache License 2.0 | 6 votes |
@Test public void testParameters() { MustacheEngine engine = MustacheEngineBuilder.newBuilder() .registerHelper("test", new AbstractHelper() { @Override public void execute(Options options) { List<Object> params = options.getParameters(); assertEquals(3, params.size()); assertEquals("1", params.get(0)); assertEquals(10, params.get(1)); assertNull(params.get(2)); assertEquals("1", options.getParameter(0, null)); assertEquals(10, options.getParameter(1, null)); assertNull(options.getParameter(4, null)); assertNull(options.getParameter(-5, null)); } }).build(); engine.compileMustache("helper_params", "{{test \"1\" this.age nonexisting}}").render(new Hammer()); }
Example #8
Source File: PartialSegmentTest.java From trimou with Apache License 2.0 | 6 votes |
@Test public void testPartialNotFound() { MustacheEngine engine = MustacheEngineBuilder.newBuilder().build(); try { engine.compileMustache("partial_not_found", "Hello,\n this partial \n\n {{>neverexisted}}") .render(null); fail("Partial does not exist!"); } catch (MustacheException e) { if (!e.getCode().equals(MustacheProblem.RENDER_INVALID_PARTIAL_KEY)) { fail("Invalid problem"); } System.out.println(e.getMessage()); } }
Example #9
Source File: NumberHelpersTest.java From trimou with Apache License 2.0 | 6 votes |
@Test public void testIsEven() { MustacheEngine engine = MustacheEngineBuilder.newBuilder() .registerHelpers(HelpersBuilder.empty().addIsEven().build()) .build(); assertEquals("even", engine.compileMustache("isEven_value", "{{#this}}{{isEven iterIndex \"even\"}}{{/this}}") .render(new String[] { "1", "2", "3" })); assertEquals("oddevenodd", engine.compileMustache("isEven_value_else", "{{#this}}{{isEven iterIndex \"even\" \"odd\"}}{{/this}}") .render(new String[] { "1", "2", "3" })); assertEquals("", engine.compileMustache("isEven_section", "{{#isEven this}}even{{/isEven}}") .render(3)); assertEquals("even", engine.compileMustache("isEven_section", "{{#isEven this}}even{{/isEven}}") .render(2)); assertCompilationFails(engine, "isEven_fail", "{{isEven}}", MustacheProblem.COMPILE_HELPER_VALIDATION_FAILURE); }
Example #10
Source File: Segments.java From trimou with Apache License 2.0 | 6 votes |
/** * * @param cachedReference * @param templateId * @param engine * @param currentTemplate If set try to lookup nested templates first * @return the template, use the cache if possible */ static Template getTemplate(AtomicReference<Template> cachedReference, String templateId, MustacheEngine engine, Template currentTemplate) { if (cachedReference != null) { Template template = cachedReference.get(); if (template == null) { synchronized (cachedReference) { if (template == null) { template = lookupTemplate(templateId, engine, currentTemplate); cachedReference.set(template); } } } return template; } return lookupTemplate(templateId, engine, currentTemplate); }
Example #11
Source File: InvokeHelperTest.java From trimou with Apache License 2.0 | 6 votes |
@Test public void testRenderingErrors() { final MustacheEngine engine = MustacheEngineBuilder.newBuilder() .registerHelpers(HelpersBuilder.empty().addInvoke().build()) .build(); MustacheExceptionAssert .expect(MustacheProblem.RENDER_HELPER_INVALID_OPTIONS) .check(() -> engine.compileMustache("invoke_method_not_found", "{{invoke m='foo'}}").render("bar")); MustacheExceptionAssert .expect(MustacheProblem.RENDER_HELPER_INVALID_OPTIONS) .check(() -> engine .compileMustache("invoke_method_ambiguous", "{{invoke 'name' 5L class='java.lang.Long' m='getLong'}}") .render("bar")); }
Example #12
Source File: FormatHelperTest.java From trimou with Apache License 2.0 | 6 votes |
@Test public void testInterpolation() { MustacheEngine engine = MustacheEngineBuilder.newBuilder() .registerHelpers(HelpersBuilder.empty().addFmt().build()) .build(); assertEquals("Hello me!", engine .compileMustache("fmt_helper01", "{{fmt 'Hello %s!' 'me'}}") .render(null)); assertEquals(" d c b a", engine.compileMustache("fmt_helper02", "{{fmt '%4$2s %3$2s %2$2s %1$2s' 'a' 'b' 'c' 'd'}}") .render(null)); assertEquals("Tuesday", engine.compileMustache("fmt_helper03", "{{fmt '%tA' this locale='en'}}") .render(LocalDateTime.of(2016, 7, 26, 12, 0))); }
Example #13
Source File: JsonElementResolverTest.java From trimou with Apache License 2.0 | 6 votes |
@Test public void testOutOfBoundIndexException() throws JsonIOException, JsonSyntaxException, FileNotFoundException { // https://github.com/trimou/trimou/issues/73 String json = "{\"numbers\": [1,2]}"; String template = "One of users is {{numbers.2}}."; final JsonElement jsonElement = new JsonParser().parse(json); MustacheEngine engine = MustacheEngineBuilder.newBuilder() .setMissingValueHandler( new ThrowingExceptionMissingValueHandler()) .omitServiceLoaderConfigurationExtensions() .setProperty(JsonElementResolver.UNWRAP_JSON_PRIMITIVE_KEY, true) .setProperty(GsonValueConverter.ENABLED_KEY, false) .addResolver(new ThisResolver()).addResolver(new MapResolver()) .addResolver(new JsonElementResolver()).build(); final Mustache mustache = engine.compileMustache("unwrap_array_index", template); MustacheExceptionAssert.expect(MustacheProblem.RENDER_NO_VALUE) .check(() -> mustache.render(jsonElement)); }
Example #14
Source File: DefaultParsingHandler.java From trimou with Apache License 2.0 | 6 votes |
@Override public void startTemplate(String name, Delimiters delimiters, MustacheEngine engine) { this.delimiters = delimiters; this.engine = engine; this.templateName = name; containerStack.addFirst(new RootSegmentBase()); skipValueEscaping = engine.getConfiguration().getBooleanPropertyValue( EngineConfigurationKey.SKIP_VALUE_ESCAPING); handlebarsSupportEnabled = engine.getConfiguration() .getBooleanPropertyValue( EngineConfigurationKey.HANDLEBARS_SUPPORT_ENABLED); start = System.currentTimeMillis(); LOGGER.debug("Start compilation of {}", new Object[] { name }); }
Example #15
Source File: InvokeHelperTest.java From trimou with Apache License 2.0 | 6 votes |
@Test public void testStaticMethod() { final MustacheEngine engine = MustacheEngineBuilder.newBuilder() .registerHelpers(HelpersBuilder.empty().addInvoke().build()) .build(); List<String> list = new ArrayList<>(); list.add("foo"); list.add("bar"); list.add("baz"); assertEquals("bazbarfoo", engine.compileMustache("invoke_static_01", "{{invoke this class='java.util.Collections' m='reverse'}}{{#each this}}{{this}}{{/each}}") .render(list)); assertEquals("war", engine.compileMustache("invoke_static_02", "{{#invoke 'WAR' class='org.trimou.ArchiveType' m='valueOf'}}{{suffix}}{{/invoke}}") .render(null)); assertEquals("1", engine.compileMustache("invoke_static_03", "{{#invoke 'MILLISECONDS' class='java.util.concurrent.TimeUnit' m='valueOf'}}{{invoke 1000l m='toSeconds'}}{{/invoke}}") .render(null)); assertEquals("war", engine.compileMustache("invoke_static_04", "{{#invoke 'WAR' class=this m='valueOf'}}{{suffix}}{{/invoke}}") .render(ArchiveType.class)); }
Example #16
Source File: JoinHelperTest.java From trimou with Apache License 2.0 | 6 votes |
@Test public void testJoinHelperValidation() { final MustacheEngine engine = MustacheEngineBuilder.newBuilder() .registerHelpers(HelpersBuilder.empty().addJoin().build()) .build(); MustacheExceptionAssert .expect(MustacheProblem.COMPILE_HELPER_VALIDATION_FAILURE) .check(() -> engine.compileMustache("join_helper_validation01", "{{join}}")); MustacheExceptionAssert .expect(MustacheProblem.RENDER_HELPER_INVALID_OPTIONS).check( () -> engine .compileMustache("join_helper_validation02", "{{join 'Me' lambda='foo'}}") .render(null)); }
Example #17
Source File: ContextConverterTest.java From trimou with Apache License 2.0 | 6 votes |
@Test public void testInvalidContextConverter() { MustacheEngine engine = MustacheEngineBuilder.newBuilder().addContextConverter(new ContextConverter() { @Override public Object convert(Object from) { return "true"; } @Override public boolean isValid() { return false; } }).build(); assertEquals("Foo", engine.compileMustache("{{this}}").render("Foo")); }
Example #18
Source File: JsonValueResolverTest.java From trimou with Apache License 2.0 | 6 votes |
@Test public void testOutOfBoundIndexException() throws FileNotFoundException { // https://github.com/trimou/trimou/issues/73 String json = "{\"numbers\": [1,2]}"; String template = "One of users is {{numbers.2}}."; JsonStructure jsonStructure = Json.createReader(new StringReader(json)) .read(); MustacheEngine engine = MustacheEngineBuilder.newBuilder() .setMissingValueHandler( new ThrowingExceptionMissingValueHandler()) .omitServiceLoaderConfigurationExtensions() .setProperty(JsonValueResolver.ENABLED_KEY, true) .setProperty(JsonProcessingValueConverter.ENABLED_KEY, false) .addResolver(new ThisResolver()).addResolver(new MapResolver()) .addResolver(new JsonValueResolver()).build(); final Mustache mustache = engine.compileMustache("unwrap_array_index", template); MustacheExceptionAssert.expect(MustacheProblem.RENDER_NO_VALUE) .check(() -> mustache.render(jsonStructure)); }
Example #19
Source File: OptionsTest.java From trimou with Apache License 2.0 | 6 votes |
@Test public void testFnAppendable() { final StringBuilder builder = new StringBuilder(); MustacheEngine engine = MustacheEngineBuilder.newBuilder() .registerHelper("test", new AbstractHelper() { @Override public void execute(Options options) { options.fn(builder); } }).build(); String literal = "This is /n a foo"; assertEquals( "", engine .compileMustache("helper_fnappendable", "{{#test}}" + literal + "{{/test}}") .render(null)); assertEquals(literal, builder.toString()); }
Example #20
Source File: MinifyListenerTest.java From trimou with Apache License 2.0 | 6 votes |
@Test public void testCustomListener() { MustacheEngine engine = MustacheEngineBuilder .newBuilder() .addMustacheListener( Minify.customListener(new AbstractMinifier() { @Override public Reader minify(String mustacheName, Reader mustacheContents) { return mustacheName.endsWith("js") ? new StringReader( "") : mustacheContents; } })).build(); assertEquals("", engine.compileMustache("mustache.js", "whatever") .render(null)); assertEquals("<html>", engine.compileMustache("foo", "<html>").render(null)); }
Example #21
Source File: PrettyTimeHelperTest.java From trimou with Apache License 2.0 | 6 votes |
@Test public void testLocale() { MustacheEngine engine = MustacheEngineBuilder.newBuilder() .omitServiceLoaderConfigurationExtensions() .setLocaleSupport(FixedLocaleSupport.from(Locale.ENGLISH)) .addResolver(new ThisResolver()) .registerHelper("pretty", new PrettyTimeHelper()).build(); // JustNow (the first time unit in the default list) has max quantity 1 min Calendar now = Calendar.getInstance(); now.add(Calendar.SECOND, -30); assertEquals(new Resources_cs().getString("JustNowPastPrefix"), engine.compileMustache("pretty_helper_locale", "{{{pretty this locale='cs'}}}").render(now)); }
Example #22
Source File: OptionsTest.java From trimou with Apache License 2.0 | 6 votes |
@Test public void testFluentVersions() { MustacheEngine engine = MustacheEngineBuilder.newBuilder().registerHelper("foo", (o) -> { o.pushAnd("foo").fnAnd().partialAnd("baz").appendAnd(" and").pop(); }).registerHelper("bar", (o) -> { o.pushAnd("bar") .fnAnd(o.getAppendable()) .partialAnd("baz", o.getAppendable()) .getValueAnd("this", value -> assertEquals("bar", value)) .sourceAnd("baz", source -> assertEquals("{{this}}", source)) .peekAnd(object -> assertEquals("bar", object)) .appendAnd(" and ") .getAppendableAnd(appendable -> { try { appendable.append("test"); } catch (IOException e) { e.printStackTrace(); } }) .popAnd(object -> assertEquals("bar", object)); }).addTemplateLocator(MapTemplateLocator.builder().put("baz", "{{this}}").build()).build(); assertEquals("bar and test", engine.compileMustache("{{bar}}").render(null)); }
Example #23
Source File: PrettyTimeHelperTest.java From trimou with Apache License 2.0 | 6 votes |
@Test public void testInterpolation() { MustacheEngine engine = MustacheEngineBuilder.newBuilder() .omitServiceLoaderConfigurationExtensions() .setLocaleSupport(FixedLocaleSupport.from(Locale.ENGLISH)) .addResolver(new ThisResolver()) .registerHelper("pretty", new PrettyTimeHelper()).build(); String expected = new Resources_en().getString("JustNowPastPrefix"); // JustNow (the first time unit in the default list) has max quantity 1 min Calendar now = Calendar.getInstance(); now.add(Calendar.SECOND, -30); assertEquals(expected, engine .compileMustache("pretty_cal", "{{pretty this}}").render(now)); assertEquals(expected, engine.compileMustache("pretty_date", "{{pretty this}}") .render(now.getTime())); assertEquals(expected, engine.compileMustache("pretty_long", "{{pretty this}}") .render(now.getTimeInMillis())); }
Example #24
Source File: OptionsTest.java From trimou with Apache License 2.0 | 6 votes |
@Test public void testGetValue() { final AtomicBoolean released = new AtomicBoolean(false); MustacheEngine engine = MustacheEngineBuilder.newBuilder() .omitServiceLoaderConfigurationExtensions() .addResolver(new AbstractResolver(1) { @Override public Object resolve(Object contextObject, String name, ResolutionContext context) { context.registerReleaseCallback( () -> released.set(true)); return "foo"; } }).registerHelper("test", new AbstractHelper() { @Override public void execute(Options options) { options.append(options.getValue("key").toString()); } }).build(); assertEquals("foo", engine .compileMustache("helper_getvalue", "{{test}}").render("bar")); assertTrue(released.get()); }
Example #25
Source File: EvalHelperTest.java From trimou with Apache License 2.0 | 6 votes |
@Test public void testHelperHandleNulls() { final MustacheEngine engine = MustacheEngineBuilder.newBuilder() .registerHelpers(HelpersBuilder.empty().addEval().build()) .build(); Map<String, Object> mappings = new HashMap<>(); Map<String, Object> data = new HashMap<>(); data.put("_mappings", mappings); assertEquals("", engine.compileMustache("{{eval '_mappings.language' locale}}").render(data)); Map<String, Object> languages = new HashMap<>(); mappings.put("language", languages); assertEquals("", engine.compileMustache("{{eval '_mappings.language' locale}}").render(data)); languages.put("de", "deu"); assertEquals("", engine.compileMustache("{{eval '_mappings.language' locale}}").render(data)); data.put("locale", "de"); assertEquals("deu", engine.compileMustache("{{eval '_mappings.language' locale}}").render(data)); }
Example #26
Source File: PartialSegmentTest.java From trimou with Apache License 2.0 | 5 votes |
@Test public void testCachedPartialSegmentNotUsed() { Map<String, String> map = new HashMap<>(); map.put("alpha", "{{>bravo}}"); map.put("bravo", "{{this}}"); MapTemplateLocator locator = new MapTemplateLocator(map); MustacheEngine engine = MustacheEngineBuilder.newBuilder() .addTemplateLocator(locator) .setProperty(EngineConfigurationKey.DEBUG_MODE, true).build(); Mustache mustache = engine.getMustache("alpha"); assertEquals("foo", mustache.render("foo")); map.put("bravo", "NOTHING"); assertEquals("NOTHING", mustache.render("foo")); }
Example #27
Source File: OptionsTest.java From trimou with Apache License 2.0 | 5 votes |
@Test public void testPeek() { MustacheEngine engine = MustacheEngineBuilder.newBuilder() .registerHelper("test", new AbstractHelper() { @Override public void execute(Options options) { options.append(options.peek().toString()); } }).build(); assertEquals("HELLO", engine.compileMustache("helper_peek", "{{test}}") .render("HELLO")); }
Example #28
Source File: ELHelperTest.java From trimou with Apache License 2.0 | 5 votes |
@Test public void testCustomELProcessorFactory() { CustomELProcessorFactory.value = Boolean.TRUE; MustacheEngine engine = MustacheEngineBuilder.newBuilder() .setProperty(ELProcessorFactory.EL_PROCESSOR_FACTORY_KEY, new CustomELProcessorFactory()).build(); assertEquals("true", engine.compileMustache("elpfcustom_01", "{{el 'foo'}}").render(null)); }
Example #29
Source File: MinifyListenerTest.java From trimou with Apache License 2.0 | 5 votes |
@Test public void testDefaultXmlListener() { MustacheEngine engine = MustacheEngineBuilder.newBuilder() .addMustacheListener(Minify.xmlListener()).build(); assertEquals( "<foo><bar>Hey FOO!</bar></foo>", engine.compileMustache("minify_xml", "<foo> <!-- My comment --> <bar>Hey {{foo}}!</bar> \n\n </foo>") .render(ImmutableMap.<String, Object> of("foo", "FOO"))); }
Example #30
Source File: InvokeHelperTest.java From trimou with Apache License 2.0 | 5 votes |
@Test public void testDefaultMethodName() { MustacheEngine engine = MustacheEngineBuilder.newBuilder() .registerHelpers(HelpersBuilder.empty() .add("substring", InvokeHelper.of("substring")) .build()) .build(); assertEquals("345", engine .compileMustache("invoke_defmethodname_01", "{{substring 3}}") .render("012345")); assertEquals("lo", engine .compileMustache("invoke_defmethodname_01", "{{substring 3 on='hello' m='whatever'}}") .render(null)); }