Search code examples
phpfat-free-framework

How to parse variable to layout


I'm trying out Fat-Free Framework, and I do not now how to parse variables to my layouts. Well somehow I do, but not the way I want. I know you can parse variables via routes, and then using set. But I have this layout where I have some specific variables which needs to be in my layout, and these will always be there, like my title and other stuff. But it doesn't make sense that I need to parse these for every route, is there some way to do this.

I did read all the documentation they have on fatfreeframework.com and searched trough google and this site, but I could not find anything specific.


Solution

  • It looks like when you say "parse", you mean "define". I'll assume your question is: "how to define variables so that they are accessible from templates?".

    There are various ways to achieve this. The basic way is to define variables using $f3->set(), then to display a template in which the defined variables will be accessible. For example:

    //index.php
    $f3->route('GET /example1',function($f3){
      $f3->set('title','my title');
      $f3->set('stuff','my stuff');
      $tpl=\Template::instance();
      echo $tpl->render('index.html');
    }};
    
    //index.html
    <h1>{{$title}}</h1>
    <p>{{$stuff}}</p>
    

    Now if you need variables commons to all routes, you can define them outside of the route scope:

    $f3->set('title','my title');//$title will be accessible from all routes
    $f3->set('stuff','my stuff');//$stuff also
    $f3->route('GET /example1',...);
    $f3->route('GET /example2',...);
    

    If you have many of those common variables and you need the possibility to modify them without changing the code, you can define them in a configuration file (.ini format):

    //index.php
    $f3->config('cfg/commons.ini');
    $f3->route('GET /example1',...);
    $f3->route('GET /example2',...);
    
    //commons.ini
    title = my title
    stuff = my stuff