Skip to content

Using erazor macro templates in a ufront project

tjrhodes edited this page Mar 23, 2012 · 2 revisions

Requirements for erazor macro templates

Preparing the Template code

Firstly make sure you have understood how to get a ufront project up and running. So you know a little about getting some data into erazor templates from a ufront controller right? Cool, let's make those runtime templates become compile time, type checked, erazor templates. Here's the template html we will be using for this example:

    <!DOCTYPE html>
    <html lang="en">
    <head>
            <meta charset="utf-8">
            <title>erazor macro templates</title>
    </head>
    <body>
            <h1>home</h1>
            <!-- note the name of the variable this template expects to use -->
            @message
    </body>
    </html>

Ok, let's stick to a simple set-up, where you are routing "/" to "home" and thus HomeController. Your runtime view is /view/home/index.html (relative to the root of your compiled, published project). Now we are switching to compile time, so your view folder needs to be next to the controller folder in your source folder. E.g. bin/view/home/index.html becomes src/view/home/index.html.

Now, here's the first change to the runtime method. Make a new haxe class called HomeView.hx and place this next to the html file in src/view/home/. Here is an example:

    package view.home;
    import erazor.macro.Template;

    // tell the erazor macro template engine what html file we want to use with this class
    @includeTemplate("index.html")

    // note the type after Template, this templates expects a string to be passed to it called message.
    // you will get compile time type checking against this information, plus when the html is parsed it will
    // check the names of the vars used inside it to make sure you aren't doing anything off :)
    class HomeView extends Template<{message:String}>
    {

    }

Integrating our templates with a ufront controller

So, we have a haxe class extending Template which supplies type information and is linked to an html template file using the macro code '@includeTemplate("myhtml.html")', now we're ready to look at the Controller code to use our new stuff. The code is a bit different to the runtime templates, but it's fairly simple stuff, here's our HomeController...

    package controller;
    // this is what produces the final output instead of ViewResult
    import ufront.web.mvc.ContentResult;
    import ufront.web.mvc.Controller;
    // this is our brand new Template class
    import view.home.HomeView;

    class HomeController extends Controller
    {

        public function index() 
        {
	        var msg = "Hey, i got generated at compile time!";
	        var homePageMarkup = new HomeView().execute({message:msg});
	        return new ContentResult(homePageMarkup);
        }

    }

That's all it takes! Enjoy :)