All Downloads are FREE. Search and download functionalities are using the official Maven repository.

htmlcompiler.compilers.templates.Thymeleaf Maven / Gradle / Ivy

There is a newer version: 5.8.0
Show newest version
package htmlcompiler.compilers.templates;

import htmlcompiler.pojos.error.InvalidTemplate;
import org.apache.maven.project.MavenProject;
import org.thymeleaf.context.IContext;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class Thymeleaf implements HtmlTemplateEngine {

    private org.thymeleaf.TemplateEngine engine;
    private IContext context;
    public Thymeleaf(final MavenProject project) {
        this.engine = new org.thymeleaf.TemplateEngine();
        final Map map = applyMavenProjectContext(applyEnvironmentContext(new HashMap<>()), project);
        this.context = new IContext() {
            public Locale getLocale() {
                return Locale.getDefault();
            }
            public boolean containsVariable(String s) {
                return map.containsKey(s);
            }
            public Set getVariableNames() {
                return map.keySet();
            }
            public Object getVariable(String s) {
                return map.get(s);
            }
        };
    }

    @Override
    public String compile(File file) throws IOException, InvalidTemplate {
        engine.process(Files.readString(file.toPath()), context);
        return null;
    }

    private static Map applyMavenProjectContext(final Map context, final MavenProject project) {
        for (final Entry entry : project.getProperties().entrySet()) {
            context.put(entry.getKey().toString(), entry.getValue());
        }
        return context;
    }
    private static Map applyEnvironmentContext(final Map context) {
        for (final Entry entry : System.getenv().entrySet()) {
            context.put(entry.getKey(), entry.getValue());
        }
        return context;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy