Guide to Implementing Slim View via Template Engine

  • Cubettech
  • Web App Development
  • 9 years ago
Guide to Implementing Slim View via Template Engine

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:

Example:

//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'));  $app->render(‘home.php’); });

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));  $app->render(‘home.php’); });

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

->TwigView.php

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’));

Example:

require ‘slim/slim.php’; require ‘View/TwigView.php’;         //initialize slim to use the TwigView handler         Slim::init(array(‘view’ => ‘TwigView’));         //Setup route         Slim::get(‘/’,function(){         $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));  slim::render(‘home.html’); }); //Run the application slim::run();

home.html file

{{body}}

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

Table of Contents

    Contact Us

    Contact

    What's on your mind? Tell us what you're looking for and we'll connect you to the right people.

    Let's discuss your project.

    Phone