@Test public void shouldNotOutputNothingIfListIsNull() throws ParseException, CompileException, RenderException { JtwigTemplate template = new JtwigTemplate("{% for item in list %}a{% endfor %}"); JtwigContext context = new JtwigContext(); context.withModelAttribute("list", null); assertThat(template.output(context), is("")); }
@Test public void emptyListShouldOutputNothing() throws ParseException, CompileException, RenderException { JtwigTemplate template = new JtwigTemplate("{% for item in list %}Item {{ item }}{% endfor %}"); JtwigContext context = new JtwigContext(); ArrayList<String> value = new ArrayList<String>(); context.withModelAttribute("list", value); assertThat(template.output(context), is("")); }
@Test public void iterateOverMap() throws ParseException, CompileException, RenderException { JtwigTemplate template = new JtwigTemplate("{% for key, value in map %}{{ key }} = {{ value }}|{% endfor %}"); JtwigContext context = new JtwigContext(); LinkedHashMap<String, String> value = new LinkedHashMap<String, String>(); value.put("one", "1"); value.put("two", "2"); value.put("three", "3"); context.withModelAttribute("map", value); assertThat(template.output(context), is("one = 1|two = 2|three = 3|")); }
@Test public void forLoopMustExposeTheLoopVariable() throws ParseException, CompileException, RenderException { JtwigTemplate template = new JtwigTemplate( "{% for item in list %}" + "{% if loop.first %}First {% elseif loop.last %}Last{% else %}I: {{ loop.index }} R: {{ loop.revindex }} {% endif %}" + "{% endfor %}"); JtwigContext context = new JtwigContext(); ArrayList<String> value = new ArrayList<String>(); value.add("a"); value.add("b"); value.add("c"); value.add("d"); value.add("e"); context.withModelAttribute("list", value); assertThat(template.output(context), is("First I: 1 R: 3 I: 2 R: 2 I: 3 R: 1 Last")); }