Fat-Free Framework – 8. Using the templating engine of the framework

Even though it’s a tiny framework, Fat-Free has a templating engine that we can use. In order to do this, instead of calling the View class, we call the Template class:

<?php

class Homepage {
  function index(){
    $f3=\Base::instance();
    $data = array();
    $data['name'] = 'avenirer';
    $data['url'] = $f3->alias('the_contact_page','who=avenirer');
    echo \Template::instance()->render('HomepageView.php','text/html',$data);
  }
}

But what can we do with this template engine? Well… Besides the fact that it’s faster to work with it, it is also safer (or at least “they say” it is).

Let’s now see how or HomepageView.php looks like:

<?php

echo 'hello from index'.'<br />';
echo '<a href="'.$url.'">'.$name.'</a>';

And how we can make it look lighter by using the templating engine:

<p>hello from index</p>
<p><a href="{{ @url }}">{{ @name }}</a></p>

Wow… Much shorter…

What is nice about the templating engine is the fact that it can use hive‘s variables directly and not by passing the values to an intermediary variable. If we return to our Homepage.php controller we can do something as follows:

<?php
class Homepage {
  function index(){
    $f3=\Base::instance();
    $f3->set('name','avenirer');
    $f3->set('url',$f3->alias('the_contact_page','who=avenirer'));
    echo \Template::instance()->render('HomepageView.php','text/html');
  }
}

But what if we have arrays?

<p>{{ @buddy[0] }}, {{ @buddy[1] }}, and {{ @buddy[2] }}</p>

More on the templating engine can be found here: https://fatfreeframework.com/views-and-templates#PHPasaTemplateEngine

Let us also talk about importing views, or “partials”. Inside your templates you can import other templates by using an “include” tag:

<include href="header.htm" />

You can also use dinamically created views that you’ve created and set in the controller:

<include href="{{@content}}" />
<include href="{{'templates/layout/'.@content}}" />

..and yet… there are many things that the template can do. Do give a visit to the Fat-Free Framework’s documentation: https://fatfreeframework.com/views-and-templates#PHPasaTemplateEngine

2 comments

  1. Do you have any example? how to implement the relationship between two or more tables with Cortex in simple steps. I really don’t understand the tutorials were explained on their github page.

    thx

  2. Great tutorial. Very simple and easy to understand. It’s much better than the actual documentation, really. When is the next parts going to be posted ?

Leave a Reply

Your email address will not be published. Required fields are marked *

No spam? * Time limit is exhausted. Please reload CAPTCHA.