Monday, June 15, 2009

Creating FreeMarker Templates

Before we can execute a template, we have to create one.

A template is basically just an HTML file with some extra bits for making minor decisions and displaying collections of data. When we create the template we decide what kind of data we'll need, but we don't know exactly what values will be assigned. That happens later, when the servlet gives the template values for the data it needs.

For the front page, let's say that we just need to know if the user is logged in or not. Eventually we'll want their name, too, but remember that we haven't put that into the datastore yet. So we'll settle for knowing if they're logged in.

In Eclipse, right click on the war directory in your project and choose New->File. Name it something like Front.ftl. The extension must be .ftl for the FreeMarker plugin to operate on it.

Now let's copy over the HTML from the project.html file, and remove the bits we don't need. We'll end up with something like this:


<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<link type="text/css" rel="stylesheet" href="Omega.css">
<title>Web Application Starter Project</title>
</head>

<body>

<h1>Web Application Starter Project</h1>

<!-- Put your RPX Sign In link here -->

<!-- Put your RPX Javascript here -->
</body>
</html>


Except that you would have actually copied your RPX Sign In link and Javascript over from the project.html file.

Now picture that if the user is signed in, we want to display a Sign Out link instead of the Sign In link. Let's just go ahead and put a Sign Out link in there, just before the Sign In link.


<a href="/signout">Sign Out</a>


We don't have a signout servlet yet, but that's okay for now. We can use an if statement inside a FreeMarker template, similar to in Java. Let's pretend that we have a variable called "loggedIn" that's true if the user is logged in.

If we do something like this:


<#if loggedIn>
<!-- Put Sign Out link here -->
<#else>
<!-- Put Sign In link here -->
</#if>


Replacing, of course, the comments with the appropriate HTML, then the template will only display one of the links, depending on the value of loggedIn.

So how does the value of loggedIn get set? That's over in our front page servlet, and the next post.

No comments:

Post a Comment