Layout Files and Velocity templating engine.

248 views
Skip to first unread message

Jake Kaad

unread,
Jun 1, 2015, 1:14:27 PM6/1/15
to spar...@googlegroups.com
Hey All,


I want to have a default "layout" page to load all of my scripts and dependencies into. From what I understand, velocity doesn't look for a default file to render through, so I kinda hacked my way around it.  I save a default layout template as an instance variable.  I then will put in the model the path to the template I would actually like to render.  

Here is an example of my route:

public class App {
  public static void main(String[] args) {
    staticFileLocation("/public");
    String layout = "templates/layout.vtl";

    get("/", (request, response) -> {
      HashMap<String, Object> model = new HashMap<String, Object>();

      model.put("todos", request.session().attribute("todos"));

      model.put("template", "templates/index.vtl");
      return new ModelAndView(model, layout);
    }, new VelocityTemplateEngine());


And here is what my layout.vtl file looks like

<!DOCTYPE html>
<html>
  <head>
    <title>Template</title>
    <link rel='stylesheet' href='app.css'>
  </head>
  <body>
    <div class="container">
      #parse( $template )
    </div>
  </body>
</html>


This feels very clunky to me, does anybody have any suggestions on how I could make this code a little bit easier to read?  

Much appreciated,

Jake

David Åse

unread,
Jun 2, 2015, 12:32:50 PM6/2/15
to spar...@googlegroups.com
You can use the $!bodyContent variable. I usually make a macro called main, and call that in all my templates. In your case:

layout.vm:

#macro(mainLayout)
<!DOCTYPE html>
<html>
  <head>
    <title>Template</title>
    <link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css
'>
    <link rel='stylesheet' href='app.css'>
  </head>
  <body>
    <div class="container">   ## consider using <main> HTML5 tag
      $!bodyContent##         ## "##" trims trailing whitespaces
    </div>
  </body>
</html>
#end
index.vm:
#@mainLayout()
<h1>Index page</h1> #end

Jake Kaad

unread,
Jun 3, 2015, 4:01:37 PM6/3/15
to spar...@googlegroups.com
That is a lot easier, thank you!
Reply all
Reply to author
Forward
0 new messages