public void testImplicitIteratorWithScope() throws IOException { Mustache test = new DefaultMustacheFactory().compile(new StringReader("{{#test}}_{{.}}_{{/test}}"), "test"); StringWriter sw = new StringWriter(); test.execute(sw, new Object() { List<String> test = Arrays.asList("a", "b", "c"); }).close(); assertEquals("_a__b__c_", sw.toString()); }
@SuppressWarnings("StatementWithEmptyBody") @Override public synchronized void init() { filterText(); Map<String, ExtendNameCode> replaceMap = new HashMap<>(); for (Code code : mustache.getCodes()) { if (code instanceof ExtendNameCode) { // put name codes in the map ExtendNameCode erc = (ExtendNameCode) code; replaceMap.put(erc.getName(), erc); erc.init(); } else if ((code instanceof WriteCode) || (code instanceof CommentCode)) { // ignore text and comments } else { // fail on everything else throw new IllegalArgumentException( "Illegal code in extend section: " + code.getClass().getName()); } } Mustache original = mf.compilePartial(partialName()); partial = (Mustache) original.clone(); Code[] supercodes = partial.getCodes(); // recursively replace named sections with replacements Set<Code> seen = new HashSet<>(); seen.add(partial); partial.setCodes(replaceCodes(supercodes, replaceMap, seen)); }
public Mustache compile(Reader reader, String file, String sm, String em) { Mustache compile = mc.compile(reader, file, sm, em); compile.init(); partialCache.remove(); return compile; }
@Test public void should_load_teamplates_with_absolute_references_using_filepath() throws Exception { File file = new File("compiler/src/test/resources/templates_filepath"); File root = new File(file, TEMPLATE_FILE).exists() ? file : new File("src/test/resources/templates_filepath"); MustacheFactory factory = new DefaultMustacheFactory(root); Mustache maven = factory.compile(TEMPLATE_FILE); StringWriter sw = new StringWriter(); maven.execute(sw, new Object() { List<String> messages = Arrays.asList("w00pw00p", "mustache rocks"); }).close(); assertEquals("w00pw00p mustache rocks ", sw.toString()); }
@Test public void testArrayOutput() throws IOException { MustacheFactory mf = new DefaultMustacheFactory(); Mustache test = mf.compile(new StringReader("{{#test}}{{#first}}[{{/first}}{{^first}}, {{/first}}\"{{value}}\"{{#last}}]{{/last}}{{/test}}"), "test"); StringWriter sw = new StringWriter(); test.execute(sw, new Object() { Collection test = new DecoratedCollection(Arrays.asList("one", "two", "three")); }).flush(); assertEquals("[\"one\", \"two\", \"three\"]", sw.toString()); }
@Test public void testObjectHandler() throws IOException { DefaultMustacheFactory mf = new DefaultMustacheFactory(); mf.setObjectHandler(new ReflectionObjectHandler() { @Override public Object coerce(Object object) { if (object instanceof Collection) { return new DecoratedCollection((Collection) object); } return super.coerce(object); } }); Mustache test = mf.compile(new StringReader( "{{#test}}{{index}}: {{#first}}first: {{/first}}{{#last}}last: {{/last}}{{value}}\n{{/test}}"), "test"); StringWriter sw = new StringWriter(); test.execute(sw, new Object() { Collection test = Arrays.asList("First", "Second", "Third", "Last"); }).flush(); assertEquals("0: first: First\n1: Second\n2: Third\n3: last: Last\n", sw.toString()); }
/** * At compile time, this function extracts the name of the variable: * {{#toJson}}variable_name{{/toJson}} */ protected static String extractVariableName(String fn, Mustache mustache, TemplateContext tc) { Code[] codes = mustache.getCodes(); if (codes == null || codes.length != 1) { throw new MustacheException("Mustache function [" + fn + "] must contain one and only one identifier"); } try (StringWriter capture = new StringWriter()) { // Variable name is in plain text and has type WriteCode if (codes[0] instanceof WriteCode) { codes[0].execute(capture, Collections.emptyList()); return capture.toString(); } else { codes[0].identity(capture); return capture.toString(); } } catch (IOException e) { throw new MustacheException("Exception while parsing mustache function [" + fn + "] at line " + tc.line(), e); } } }
@SuppressWarnings("unchecked") protected void handleFunction(Writer writer, Function function, List<Object> scopes) throws IOException { String value; Object newtemplate = function.apply(null); if (newtemplate == null) { value = ""; } else { String templateText = newtemplate.toString(); StringWriter sw = new StringWriter(); // The specification says that template functions need to be parsed with the default delimiters // Running Interpolation - Alternate Delimiters - A lambda's return value should parse with the default delimiters.: failed! // TemplateContext newTC = new TemplateContext(tc.startChars(), tc.endChars(), tc.file(), tc.line(), tc.startOfLine()); TemplateContext newTC = new TemplateContext(DEFAULT_SM, DEFAULT_EM, tc.file(), tc.line(), tc.startOfLine()); df.getFragment(new FragmentKey(newTC, templateText)).execute(sw, scopes).close(); value = sw.toString(); } execute(writer, value); }
public static void main(String[] args) throws MustacheException, IOException { Writer writer = new OutputStreamWriter(System.out); MustacheFactory mf = new DefaultMustacheFactory(); Mustache mustache = mf.compile(new StringReader("{{hello}}, {{world}}!"), "helloworld"); mustache.execute(writer, new HelloWorld()); writer.flush(); } }
@Override public void writeTo(final Mustache mustache, final Viewable viewable, final MediaType mediaType, final MultivaluedMap<String, Object> httpHeaders, final OutputStream out) throws IOException { Charset encoding = setContentType(mediaType, httpHeaders); mustache.execute(new OutputStreamWriter(out, encoding), viewable.getModel()).flush(); } }
@Override public void render(View view, Locale locale, OutputStream output) throws IOException { try { final MustacheFactory mustacheFactory = useCache ? factories.get(view.getClass()) : createNewMustacheFactory(view.getClass()); final Mustache template = mustacheFactory.compile(view.getTemplateName()); final Charset charset = view.getCharset().orElse(StandardCharsets.UTF_8); try (OutputStreamWriter writer = new OutputStreamWriter(output, charset)) { template.execute(writer, view); } } catch (Throwable e) { throw new ViewRenderException("Mustache template error: " + view.getTemplateName(), e); } }
@Override public Code[] getCodes() { return partial == null ? null : partial.getCodes(); }
public Mustache getFragment(FragmentKey templateKey) { Mustache mustache = templateCache.computeIfAbsent(templateKey, getFragmentCacheFunction()); mustache.init(); return mustache; }
@Override public Mustache compile(String name) { Mustache mustache = mustacheCache.computeIfAbsent(name, getMustacheCacheFunction()); mustache.init(); return mustache; }
@Test public void should_handle_more_than_one_level_of_partial_nesting() throws Exception { MustacheFactory factory = new DefaultMustacheFactory(root); Mustache maven = factory.compile(TEMPLATE_FILE); StringWriter sw = new StringWriter(); maven.execute(sw, new Object() { List<String> messages = Arrays.asList("w00pw00p", "mustache rocks"); }).close(); assertEquals("w00pw00p mustache rocks ", sw.toString()); }
@Test public void testIndexLastFirst() throws IOException { MustacheFactory mf = new DefaultMustacheFactory(); Mustache test = mf.compile(new StringReader( "{{#test}}{{index}}: {{#first}}first: {{/first}}{{#last}}last: {{/last}}{{value}}\n{{/test}}"), "test"); StringWriter sw = new StringWriter(); test.execute(sw, new Object() { Collection test = new DecoratedCollection(Arrays.asList("First", "Second", "Third", "Last")); }).flush(); assertEquals("0: first: First\n1: Second\n2: Third\n3: last: Last\n", sw.toString()); }
/** * At compile time, this function extracts the name of the variable: * {{#toJson}}variable_name{{/toJson}} */ protected static String extractVariableName(String fn, Mustache mustache, TemplateContext tc) { Code[] codes = mustache.getCodes(); if (codes == null || codes.length != 1) { throw new MustacheException("Mustache function [" + fn + "] must contain one and only one identifier"); } try (StringWriter capture = new StringWriter()) { // Variable name is in plain text and has type WriteCode if (codes[0] instanceof WriteCode) { codes[0].execute(capture, Collections.emptyList()); return capture.toString(); } else { codes[0].identity(capture); return capture.toString(); } } catch (IOException e) { throw new MustacheException("Exception while parsing mustache function [" + fn + "] at line " + tc.line(), e); } } }
@Test public void testAbstractClass() throws IOException { final List<Container> containers = new ArrayList<>(); containers.add(new Container(new Foo())); containers.add(new Container(new Bar())); HashMap<String, Object> scopes = new HashMap<>(); Writer writer = new OutputStreamWriter(System.out); MustacheFactory mf = new DefaultMustacheFactory(); Mustache mustache = mf.compile(new StringReader("{{#containers}} {{foo.value}} {{/containers}}"), "example"); scopes.put("containers", containers); mustache.execute(writer, scopes); writer.flush(); }
public Code[] getCodes() { return mustache == null ? null : mustache.getCodes(); }