Total Pageviews

2020/06/10

[Java] [Apache Freemarker] How to get the first and the last item in ftl?

Problem
How to get the first and the last item in ftl?

How-To
A simple ftl example:

<#list rows as row>
<#if row?is_first>
表頭:${row.name}
<#elseif row?is_last>
表尾:${row.name}
<#else>
${row.name}
</#if>
</#list>


Test case:

package com.test.tool.filegenerator.ftl;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.Builder;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RunWith(SpringRunner.class)
@Slf4j
public class FreemarkerRowTest {

    private Configuration cfg;

    @Before
    public void init() {
        cfg = new Configuration(Configuration.VERSION_2_3_23);
        cfg.setClassForTemplateLoading(this.getClass(), "/");
    }

    @Test
    public void test() throws IOException, TemplateException {
        try (Writer file = new FileWriter(new File("C:/row_test.txt"));) {
            Template template = cfg.getTemplate("ftl/row_test.ftl");

            Map<String, Object> data = new HashMap<>();
            List<TestData> rows = createDummyData();
            rows.stream().forEach(r -> log.debug(r.getName()));

            data.put("rows", rows);

            template.process(data, file);
        } catch (IOException | TemplateException e) {
            throw e;
        }
    }

    private List<TestData> createDummyData() {
        List<TestData> data = new ArrayList<>();
        data.add(TestData.builder().name("apple").build());
        data.add(TestData.builder().name("avocado").build());
        data.add(TestData.builder().name("banana").build());
        data.add(TestData.builder().name("cherry").build());
        data.add(TestData.builder().name("coconut").build());
        data.add(TestData.builder().name("durian").build());

        return data;
    }

    @Builder
    @Getter
    public static class TestData {
        private String name;
    }

}


No comments: