Guide to Implementing Slim View via Template Engine

September 04, 2015

Slim a Micro Framework for PHP
As we discussed about the basics of slim framework in my first blog: Slim Micro Framework Overview, we can choose slim for building REST APIs as well as Website building. Here I would like to introduce Slim View.
A Slim application view is a subclass of \Slim\View.

Here is the simplest use of the Slim view:


//Create the Slim app Object
$app = new \Slim\Slim(array(
‘debug’=> true
//Create a route for the home page
	$app->get(‘/’,function () use ($app){
        	  $app->view()->setData(array('foo' => 'bar'));

We can pass values as array like this,

//Create a route for the home page
	$app->get(‘/’,function () use ($app){
        	  $app->view()->setData(array('foo' =>$array));

Custom View

A Custom view is a subclass of \Slim\View.We can use any third party libraries like Twig ,Smarty etc…
Twig Template Engine:

1.Download Twig
2.Decompress Twig into your project folder.

Project Structure will be like this,

    • .htaccess
    • index.php
    • Slim Folder
    • tests Folder
    • Twig Folder
    • View Folder


3.Open TwigView.php file and edit $twigDirectory variable null to whatever your Twig directory called.

4.Open index.php file and add following codes,

require ‘View/TwigView.php’;
//initialize slim to use the TwigView handler
Slim::init(array(‘view’ => ‘TwigView’));


require ‘slim/slim.php’;
require ‘View/TwigView.php’;
        	//initialize slim to use the TwigView handler
        	Slim::init(array(‘view’ => ‘TwigView’));
        	//Setup route
        	$title = “My App”;
$body = “This is my first application”;
//set data to be passed to the view template.
 slim::view()->setData(array('title' =>$title,'body' =>$body));
//Run the application

home.html file


Wrapping Up

We can use either Slim-Extras or any templating engine for slim application.Twig template engine is used for the above example.You can use this component to create and render in your slim web applications.

Know More About This Topic from our Techies

What Are You Missing in Your Web Application Project and Why Do We Recommend Laravel
Why Laravel Application Development Is Not a Piece of Cake for Everyone
Why Are Web Applications Necessary for Emerging Businesses?
Creating animations in Flutter by using Rive
Flutter's Animation Support
Motion UI SaaS Library for Creating Flexible UI And Transitions

Latest Post

Get a free quote