Skip to content

Instantly share code, notes, and snippets.

@000407
Forked from nhylated/Output
Last active November 28, 2019 04:46
Show Gist options
  • Select an option

  • Save 000407/9f6c33d8e889697983d80814e7f349b5 to your computer and use it in GitHub Desktop.

Select an option

Save 000407/9f6c33d8e889697983d80814e7f349b5 to your computer and use it in GitHub Desktop.
Example for iterating over a Map of Collections using the Pebble Java templating library
<h2>2001</h2>
<p>A Space Odyssey</p>
<h2>1990</h2>
<p>1990-1</p>
<p>1990-2</p>
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.mitchellbosecke.pebble.PebbleEngine;
import com.mitchellbosecke.pebble.template.PebbleTemplate;
public class Test {
// Example for: https://github.com/mbosecke/pebble/issues/55
public static void main(String args[]) throws Exception {
Map<Integer, List<Article>> articles = new HashMap<>(); // <year, article>
articles.put(1990, Arrays.asList(new Article[] {new Article("1990-1"), new Article("1990-2")}));
articles.put(2001, Arrays.asList(new Article[] {new Article("A Space Odyssey")}));
Map<String, Object> context = new HashMap<>();
context.put("articles", articles);
Writer writer = new StringWriter();
PebbleTemplate compiledTemplate = (new PebbleEngine()).getTemplate("test.peb");
compiledTemplate.evaluate(writer, context);
System.out.println(writer.toString());
}
}
class Article {
final String title;
public Article(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
}
{% for entry in articles %}
<h2>{{ entry.key }}</h2>
{% for article in entry.value %}
<p>{{ article.title }}</p>
{% endfor %}
{% endfor %}
@000407
Copy link
Author

000407 commented Nov 28, 2019

articles.entrySet is not working. Replaced with articles

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment