Thursday, 11 July 2024

Java Template Engine Pebble is fast

2 Million renderings took 0.875s

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import io.pebbletemplates.pebble.PebbleEngine;
import io.pebbletemplates.pebble.loader.ClasspathLoader;
import io.pebbletemplates.pebble.template.PebbleTemplate;

public class HtmlExporter {


    public String export() {
        PebbleEngine engine = new PebbleEngine.Builder()
                .loader(new ClasspathLoader())
                .build();
        PebbleTemplate compiledTemplate = engine.getTemplate("templates/home.html");

        Map context = new HashMap<>();
        context.put("websiteTitle", "Title :-)");
        context.put("content", "Mitchell");

        Map name = new HashMap<>();
        name.put("first", "Tom");
        name.put("last", "Stadelmann");

        context.put("name", name);

        Writer writer = new StringWriter();
        try {
            compiledTemplate.evaluate(writer, context);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        run(compiledTemplate);

        return writer.toString();
    }

    public void run(PebbleTemplate compiledTemplate) {
        var start = System.currentTimeMillis();

        for (int i = 0; i < 2000000; i++) {
            Map context = new HashMap<>();
            context.put("websiteTitle", "Title :-)");
            context.put("content", "Mitchell");

            Map name = new HashMap<>();
            name.put("first", "Tom");
            name.put("last", "Me");

            context.put("name", name);

            Writer writer = new StringWriter();
            try {
                compiledTemplate.evaluate(writer, context);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        var end = System.currentTimeMillis();
        System.out.println("Time: " + (end - start));
    }
}
<html>

<head>
    <title>{{ websiteTitle }}</title>
</head>

<body>
    {{ content }}

    {{ name.first }}
    {{ name.last }}
</body>

</html>

No comments:

Post a Comment

Parse Wikipedia dump

""" This module processes Wikipedia dump files by extracting individual articles and parsing them into a structured format, ...