How to Use Twig Templating in Slim

in #utopian-io6 years ago (edited)

twigh.png

image source

This time I will return to discuss about micro framework slim, as we know. slim is not made for powerfull, but slim can be very powerful when it adds third party libraries that match what we need. because on the basis of his slim is more recommended to build an API.
but does not close the possibility of slim can also be used worth its other PHP framework like Laravel, Code Igneter, and others. because slim is a microframework. slim does not have templating system, So what if we want to use Slim to set its template system, for that I will share to you how to use Twig in Slim for Third party templating. we just start the tutorial this time.

What Will I Learn?

  • Download Package With Composer
  • Basic Container in Slim
  • Use Twig to Templating
  • Passing Parameter in Twig

Requirements

  • Install Composer and Slim
  • Connection Internet
  • Basic Php Oop
  • Basic Html and Css

Difficulty

  • Intermediate

Install Twig and Register it

The first step we will install twig, I hope you have installed Slim before it. You can install it like this. open you command promp in your folder project.


composer require slim/twig-view
Screenshot_8.png.

And after installation , I created index.php. This my file


<?php
require __DIR__ .'./vendor/autoload.php';
$app = new Slim\App;
$app->get('/',function($request,$response){
    return "Hello World";
});
$app->run();

This simple code I just created to make sure all the installation process goes well, and if there is no error then we will see response "hello word" from routing "/"

Basic Container

Container is a place to store the packages from the outside that we can use in all slim parts. We use container like this this way. the variable $container is just a name of variable but try to remain relevant with its function.

$container = $app->getContainer();


I will make an example to register container, and give function.


$container['hello'] =  function (){
    echo " Hello world, I'm from container Slim";
};

$container['hello'] : I registered a container named 'hello'. so later if we want to call the function that is in the container we just use $this-> hello . Now we can use the container in our routing.
$app->get('/',function($request,$response){
$this->hello;
});

And the interesting thing is if we call $this-> hello many times, we will not execute this function many times.

Use Twig in Slim

After we install twig and learn a bit about the container we will start using twig in slim. the first thing we will do is to register the twig,


$container['view'] = function ($container) {
    $view = new \Slim\Views\Twig(__DIR__'./templates', [
        'cache' => 'path/to/cache'
    ]);
    // Instantiate and add Slim specific extension
    $basePath = rtrim(str_ireplace('index.php', '', $container['request']->getUri()->getBasePath()), '/');
    $view->addExtension(new Slim\Views\TwigExtension($container['router'], $basePath));
    return $view;
};

$container[ 'view' ] : Once again this is our key later we how to use the function in it by way of $this-> view.


$view = new \Slim\Views\Twig(__DIR__'./templates', [
        'cache' => 'path/to/cache'
    ]);

This is how you set the location of your template, in this tutorial I created a folder with the name of the template, but you can change it with the location you want.

$basePath = rtrim(str_ireplace('index.php', '', $container['request']->getUri()->getBasePath()), '/');
$view->addExtension(new Slim\Views\TwigExtension($container['router'], $basePath));

With this line of code, we can set the base URL and path for function.

Using Twig
After all the setup is complete we can directly use twig in our routing


$app->get('/',function($request,$response){
    return $this->view->render($response,'home.twig');
});

return $this->view->render($response,'home.twig'); : Do not forget we have to return, the name of functions is render(). We have two parameters, -First parameters is $response this is mandatory . - Second parameter is the view that we want to show, in this tutorial I show one file that is home.twig, extension can be .html

I created a file that is home.twig which is in the templates folder.
Screenshot_11.png

home.twig

<h1>Hi World , I'm Using Templating from Twig</h1>

Screenshot_12.png

Passing Parameter in Twig

Another interesting function in twig is that we can pass or mempassing data to our template. I will give you an example, I will create a new routing to demonstrate it.


$app->get('/forum[/{param_title}]',function($request,$response,$args){
    return $this->view->render($response,'home.twig',[
        'title' =>$args['param_title']
    ]);
});

$app->get('/forum[/{param_title}]',function($request,$response,$args){});: This way to passing params [/{param_title} and param_title is the name of params. ,function($request,$response,$args) We need to add one additional parameter, that is $args .
'title' =>$args['param_title'] : the key of title is the name we will pass into the twig template, and the param_title is the name of parameter routes.

home.twig

<h1>
    Hi {{param_title}}, I'm Using Templating from Twig
</h1>

Screenshot_13.png

We have finished using twig as templating in slim and know the system in use there is twig, you can explore more about twig, hopefully this tutorial can be useful for you. enough of me, see you in the next post. thank you

Curriculum



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Thank you for the contribution. It has been approved.

You can contact us on Discord.
[utopian-moderator]

Hey @deathwing, I just gave you a tip for your hard work on moderation. Upvote this comment to support the utopian moderators and increase your future rewards!

1UP-Kayrex_tiny.png

You've got upvoted by Utopian-1UP!

You can give up to ten 1UP's to Utopian posts every day after they are accepted by a Utopian moderator and before they are upvoted by the official @utopian-io account. Install the @steem-plus browser extension to use 1UP. By following the 1UP-trail using SteemAuto you support great Utopian authors and earn high curation rewards at the same time.


1UP is neither organized nor endorsed by Utopian.io!

Hey @alfarisi94 I am @utopian-io. I have just upvoted you!

Achievements

  • WOW WOW WOW People loved what you did here. GREAT JOB!
  • You have less than 500 followers. Just gave you a gift to help you succeed!
  • Seems like you contribute quite often. AMAZING!

Community-Driven Witness!

I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!

mooncryption-utopian-witness-gif

Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x

Coin Marketplace

STEEM 0.28
TRX 0.12
JST 0.032
BTC 69516.43
ETH 3791.51
USDT 1.00
SBD 3.84