added fromtpage
This commit is contained in:
@@ -0,0 +1,57 @@
|
||||
package de.srsoftware.widerhall.web;
|
||||
|
||||
import de.srsoftware.widerhall.Configuration;
|
||||
import org.stringtemplate.v4.STGroup;
|
||||
import org.stringtemplate.v4.STRawGroupDir;
|
||||
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.util.Map;
|
||||
|
||||
import static de.srsoftware.widerhall.Util.t;
|
||||
|
||||
public abstract class TemplateServlet extends HttpServlet {
|
||||
private STGroup templates;
|
||||
private final String baseDir;
|
||||
|
||||
public TemplateServlet(){
|
||||
var config = Configuration.instance();
|
||||
baseDir = config.baseDir();
|
||||
loadTemplates();
|
||||
}
|
||||
|
||||
protected String loadFile(String filename, HttpServletResponse resp) {
|
||||
var path = String.join(File.separator,baseDir,"static",filename);
|
||||
var file = new File(path);
|
||||
if (!file.exists()) return t("File {} does not exist!",filename);
|
||||
try {
|
||||
var content = Files.readString(file.toPath());
|
||||
resp.getWriter().println(content);
|
||||
} catch (IOException e) {
|
||||
return t("Failed to load file '{}'!",filename);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
protected String loadTemplate(String path, Map<String, ? extends Object> data, HttpServletResponse resp) {
|
||||
var template = templates.getInstanceOf(path);
|
||||
if (template != null){
|
||||
try {
|
||||
template.add("data",data);
|
||||
resp.getWriter().println(template.render());
|
||||
return null;
|
||||
} catch (IOException e) {
|
||||
return t("Failed to load template '{}'",path);
|
||||
}
|
||||
}
|
||||
return t("No template for path '{}'!",path);
|
||||
}
|
||||
|
||||
protected void loadTemplates() {
|
||||
var templateDir = String.join(File.separator,baseDir,"static","templates");
|
||||
templates = new STRawGroupDir(templateDir,'«','»');
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user