Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
haXe 2 Beginner's Guide

You're reading from  haXe 2 Beginner's Guide

Product type Book
Published in Jul 2011
Publisher
ISBN-13 9781849512565
Pages 288 pages
Edition 1st Edition
Languages

Table of Contents (21) Chapters

haxe 2
Credits
Foreword
About the Author
About the Reviewers
www.PacktPub.com
Preface
1. Getting to know haXe 2. Basic Syntax and Branching 3. Being Cross-platform with haXe 4. Understanding Types 5. The Dynamic Type and Properties 6. Using and Writing Interfaces, Typedefs, and Enums 7. Communication Between haXe Programs 8. Accessing Databases 9. Templating 10. Interfacing with the Target Platform 11. A Dynamic Website Using JavaScript 12. Creating a Game with haXe and Flash Pop Quiz Answers Index

Chapter 9. Templating

Using templates.

Templates are a very useful feature of haXe. They help the developer with his job of presenting data to the user by making it easy to repeat some parts of a view (or page) and by allowing some branching depending on data.

As developers our job is to create programs that allow the manipulation of data. That's the basis of our job, but beyond this part of the job, we must also be able to present that data to the user. Programs that don't have a user interface exist, but since you are reading this book about haXe, there is a greater chance that you are mostly interested in web applications, and almost all web applications have a User Interface of some kind. However, these can also be used to create XML documents for example.

In this chapter, we will cover templating by talking about:

  • The included haxe.Template class

  • The syntax used by the templating system

  • How data is passed to the templating system

  • How a template can execute some actions

So if you are ready...

Introduction to the haxe.Template class


The haXe library comes with the haxe.Template class. This class allows for basic, yet quite powerful, templating: as we will see, it is not only possible to pass some data to it, but also possible to call some code from a template.

Templates are particularly useful when you have to present data—in fact, you can, for example, define a template to display data about a user and then iterate over a list of users displaying this template for each one.

We will see how this is possible during this chapter and we will see what else you can do with templates. We will also see that it is possible to change what is displayed depending on the data and also that it is easy to do some quite common things such as having a different style for one row out of two in a table.

The haxe.Template is really easy to use—you just have to create an instance of it passing it a String that contains your template's code as a parameter. Then it is as easy as calling the execute method...

Time for action – Executing code from a template


Even though templates can't contain haXe code, they can make calls to so-called "template macros". Macros are defined by the developer and, just like data they are passed to the template.execute function. In fact, they are passed exactly in the same way, but as the second parameter.

Calling them is quite easy, instead of surrounding them with :: we will simply prefix them with $$, we can also pass them as parameters inside parenthesis. So, let's take our preceding sample and add a macro to display the number of workers in a department.

First, let's add the function to our Main class:

   public static function displayNumberOfWorkers(resolve : String->Dynamic, department : Department)
   {
      return department.workers.length + " workers";
   }

Note that the first argument that the macro will receive is a function that takes a String and returns a Dynamic. This function will allow you to retrieve the value of an expression in the context from...

Integrating subtemplates


Sub-templates do not exist as such in the templating system.

The fact is that you can include sub-templates into a main template, which is not a rare process. Some frameworks, not only in haXe, have even made this standard behavior.

So, there are two ways of doing this:

  1. Execute the sub-template, store its return value, and pass it as a property to the main template when executing it.

  2. Create a macro to execute the sub-template and return its value. This way you just have to call the macro whenever you want to include your sub-template in your main template.

Creating a blog's front page


In this section, we are going to create a front page for a blog by using the haxe.Template class.

We will also use the SPOD system to retrieve posts from the database.

Time for action – Creating our SPOD class


First, let's create a very simple SPOD class representing our blog posts.

Add this code to Post.hx:

class Post extends neko.db.Object
{
   public var id : Int;
   public var title : String;
   public var body : String;
   
   public static var manager = new neko.db.Manager<Post>(Post);
}

You also have to create the corresponding table in your SQL database. You can create it and name it "myBlog".

In order to do so, you can use the following SQL statement:

CREATE TABLE  'Post' (
'id' INT NOT NULL AUTO_INCREMENT,
'title' TEXT NOT NULL,
'body' LONGTEXT NOT NULL,
PRIMARY KEY (  'id' )
) ENGINE = MYISAM;

Once you have done this, our SQL database is set up correctly and we have objects to work with. You may want to populate it with some dumb posts:

INSERT INTO  'expressCafe'.'Post' (
'id' ,
'title' ,
'body'
)
VALUES (
NULL ,  'First Post',  'Hi, this is the first post of this blog!'
), (
NULL ,  'Second post',  'This is the second post in a not so long series...

Time for action – Connecting to the database


In our main function, let's initiate the connection to our database and the SPOD system:

import Post;

class Main
{   
   public static function main()
   {
      //Parameters to connect to the MySQL database
      var cnx = neko.db.Mysql.connect({ 
            host : "localhost",
            port : 3306,
            database : "myBlog",
            user : "root",
            pass : "",
        });
      
      //Initialize the SPOD system
        neko.db.Manager.cnx = cnx;
        neko.db.Manager.initialize();


      //We've done our processing, let's clean things and disconnect
        neko.db.Manager.cleanup();
        cnx.close();
   }
}

When doing this, we can successfully connect to the database although it won't do anything at the moment.

Now, let's just retrieve our posts from the database by simply adding this:

var posts = Post.manager.all();

We now have the following:

import Post;

class Main
{   
   public static function main()
   {
  ...

Time for action – Creating our template


Now, let's create a template that will simply take an object with the property posts to hold our list of posts.

Add this code to your template.html file:

<html>
   <head>
      <title>List of Posts</title>
   </head>
   <body>
      <!-- Simply display a greeting -->
      <h1>Hi and welcome on my blog!</h1>
      <!-- Iterate over all Posts -->
      ::foreach posts::
         <!-- Display's the blog post's title -->
         <h2>::title::</h2>
         <!-- Display's the blog post's body -->
         <div>::body::</div>
      ::end::
   </body>
</html>

You will also want to include this file as a resource named template.

To do so, just add the following to your compilation command:

-resource template.html@template

That's all it takes.

Time for action – Reading the template from resources


To read our template from resource and store it, we will simply add these lines of code:

var templateCode : String;
templateCode = haxe.Resource.getString("template");

So, we now have the following:

import Post;

class Main
{   
   public static function main()
   {
      //Parameters to connect to the MySQL database
      var cnx = neko.db.Mysql.connect({ 
            host : "localhost",
            port : 3306,
            database : "myBlog",
            user : "root",
            pass : "",
        });
      
      //Initialize the SPOD system
        neko.db.Manager.cnx = cnx;
        neko.db.Manager.initialize();

      var posts = Post.manager.all();

      var templateCode : String;
      templateCode = haxe.Resource.getString("template");

      //We've done our processing, let's clean things and disconnect
        neko.db.Manager.cleanup();
       
 cnx.close();
   }
}

Time for action – Executing the template


Now that we have loaded our template's code, we will want to execute it.

In order to do that, we have to take the following steps:

  1. Create an instance of haxe.Template passing it the value of templateCode.

  2. Pass an object with a property named posts and having our List of Posts, as a value so that they can be processed by our template.

  3. Execute our template.

  4. Print its result.

The first step is done easily with the following line of code:

var template = new haxe.Template(templateCode);

The second step can be accomplished this way:

var context = {posts : posts};

Executing the template is just as simple and we don't even need to pass it any macro. We just need to do the following:

var result = template.execute(context);

Finally, you certainly must have guessed it, to print the result we will just do the usual:

neko.Lib.print(result);

So, our complete Main class is:

import Post;

class Main
{   
   public static function main()
   {
      //Parameters to connect to the...

Time for action – Testing the result


You can simply execute this program and you should get the following output:

<html>
   <head>
      <title>List of Posts</title>
   </head>
   <body>
      <!-- Simply display a greeting -->
      <h1>Hi and welcome to my blog!</h1>
      <!-- Iterate over all Posts -->
      
         <!-- Displays the blog post's title -->
         <h2>First Post</h2>
         <!-- Displays the blog post's body -->
         <div>Hi, this is the first post of this blog!</div>
      
         <!-- Displays the blog post's title -->
         <h2>Second post</h2>
         <!-- Displays the blog post's body -->
         <div>This is the second post in a not so long series of articles.</div>
      
         <!-- Displays the blog post's title -->
         <h2>Third post</h2>
         <!-- Displays the blog post's body -->...

Summary


In this chapter, we've been talking about the haXe's standard templating system. As we've seen, it's not difficult to use and allows one to do quite a lot of interesting things such as easily generating an HTML page or generating other kind of text-files such as XML files (and even any kind of interface that uses XML as a describing language).

Specifically, we covered how to instantiate templates and give a context to them. We've also learnt how to do testing and branching in templates and calling code from them.

This chapter, although quite simple, exposes important information that you will certainly use many times while developing applications.

Also, remember that you cannot access an object's property using a template. This is a very important limitation of haxe.Template.

Now that we've learned about templates we're ready to learn about how to interface haXe with the platform you're targeting.

lock icon The rest of the chapter is locked
You have been reading a chapter from
haXe 2 Beginner's Guide
Published in: Jul 2011 Publisher: ISBN-13: 9781849512565
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime}