Created
January 21, 2015 17:27
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<h2>2001</h2> | |
<p>A Space Odyssey</p> | |
<h2>1990</h2> | |
<p>1990-1</p> | |
<p>1990-2</p> | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{% for entry in articles.entrySet %} | |
<h2>{{ entry.key }}</h2> | |
{% for article in entry.value %} | |
<p>{{ article.title }}</p> | |
{% endfor %} | |
{% endfor %} |
{% for entry in articles.entrySet %}
wouldn't work. It should be {% for entry in articles %}
.
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
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