Skip to content

Instantly share code, notes, and snippets.

@nhylated
Created January 21, 2015 17:27
Show Gist options
  • Save nhylated/a148ad6e939cdc6fa699 to your computer and use it in GitHub Desktop.
Save nhylated/a148ad6e939cdc6fa699 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.entrySet %}
<h2>{{ entry.key }}</h2>
{% for article in entry.value %}
<p>{{ article.title }}</p>
{% endfor %}
{% endfor %}
@henriquedroog
Copy link

How can I get value by key. i.g. articles.get("key")? I tried to find out on pebble documentation but I didn't.

Regards

Henrique

@000407
Copy link

000407 commented Nov 28, 2019

{% for entry in articles.entrySet %} wouldn't work. It should be {% for entry in articles %}.

@apws
Copy link

apws commented Nov 17, 2021

thanks for this example of Pebble and the correction by 000407

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