Fork me on GitHub

Html templating

Well. HTML is at the core of this Internet thing. Ninja uses Freemarker as templating engine.

If you want to know all the advanced stuff you can do with Freemarker please check out their excellent manual.

Basic HTML templating

Templates are stored in folder views/ .

And a basic template like - for instance /views/basic.ftl.html simply looks like:

<html>
    <head>
        <title>My title</title>
    </head>
<html>

Does not look too special. And it is not.

By default, Freemarker template files must end with .ftl.html, but an other extension can be defined by setting a property freemarker.suffix in your configuration file.

Using subviews nested templates

Usually you want to reuse parts of your application. Let's say a body. And a footer. Freemarker makes that quite simple.

Let's begin with a layout that will be re-used by many views - defaultLayout.ftl.html:

<#macro myLayout title="Layout example">
<!DOCTYPE html>
<html lang="en">
<head>
    <title>${title}</title>
<body>

    <#nested/>

    <#include "footer.ftl.html"/>

</body>
</html>
</#macro>

<#macro myLayout title="Layout example"> defines a variable $title a default title for it. Nesting other views into it is done by <#nested/>. And including other templates can be accomplished via <#include "footer.ftl.html"/>.

footer.ftl.html looks like:

<hr>
<footer>
    <p>Company </p>
</footer>

And the main view basic.ftl.html then looks like:

<#import "defaultLayout.ftl.html" as layout> 
<@layout.myLayout "Home page">    

    <h1>my text</h1>

</@layout.myLayout>

We import our main template <#import "defaultLayout.ftl.html" as layout> and redefine the default title to “Home Page”. The rest of the template will be included at <#nested/>.