sparkjava with templates

103 views
Skip to first unread message

赵坤

unread,
Jan 20, 2017, 10:47:53 AM1/20/17
to sparkjava
After I add templates dependency to pom.xml:

<dependency>
 
<groupId>com.sparkjava</groupId>
 
<artifactId>spark-template-freemarker</artifactId>
 
<version>2.3</version>
</dependency>

So far, I want to know where should I put hello.mustache and hello.ftl to which folders ? 

src/main/resources/hello.ftl ?

But, This path not working. Should I add the code ?

FreeMarkerEngine freeMarkerEngine = new FreeMarkerEngine();
Configuration freeMarkerConfiguration = new Configuration();
freeMarkerConfiguration
.setTemplateLoader(new ClassTemplateLoader(App.class, "/"));
freeMarkerEngine
.setConfiguration(freeMarkerConfiguration);

After specified the public resource folder, How to config the templates path ? This problem really annoyed me.

if (LOCAL) {
   
String projectDir = System.getProperty("user.dir");
   
String staticDir = "/src/main/resources/public";
   
Spark.staticFiles.externalLocation(projectDir + staticDir);
} else {
   
Spark.staticFiles.location("/public");
}

Should I put the template to 

src/main/resources/public/hello.ftl ?

Should I configure freemarker to :

freeMarkerConfiguration.setTemplateLoader(new ClassTemplateLoader(App.class, "/public"));

But It still dit not work ... How to config freemarkder, and which folder should I put the templates to?

Wilson MacGyver

unread,
Feb 21, 2017, 7:07:14 PM2/21/17
to sparkjava
you put the template in /src/resources/templates

but you don't serve it yourself using static file serving. it's handled automatically by spark


you do it in the code like 

get("template-example", (req, res) -> {
    Map<String, Object> model = new HashMap<>();
    return new FreeMarkerEngine().render(
new ModelAndView(model, "path-to-template") ); });



if the template is at /src/resources/templates/hello.ftl

you'd call it with new ModelAndView(model, "hello.ftl")
Reply all
Reply to author
Forward
0 new messages