This repository contains custom View classes for the template frameworks

Overview

Slim Views

This repository contains custom View classes for the template frameworks listed below. You can use any of these custom View classes by either requiring the appropriate class in your Slim Framework bootstrap file and initialize your Slim application using an instance of the selected View class or using Composer (the recommended way).

Slim Views only officially support the following views listed below.

  • Smarty
  • Twig

How to Install

using Composer

Install in your project by running the following composer command:

$ php composer require slim/views

Smarty

How to use


require 'vendor/autoload.php';

$app = new \Slim\Slim(array(
    'view' => new \Slim\Views\Smarty()
));

To use Smarty options do the following:

$view = $app->view();
$view->parserDirectory = dirname(__FILE__) . 'smarty';
$view->parserCompileDirectory = dirname(__FILE__) . '/compiled';
$view->parserCacheDirectory = dirname(__FILE__) . '/cache';

Twig

How to use


require 'vendor/autoload.php';

$app = new \Slim\Slim(array(
    'view' => new \Slim\Views\Twig()
));

To use Twig options do the following:

$view = $app->view();
$view->parserOptions = array(
    'debug' => true,
    'cache' => dirname(__FILE__) . '/cache'
);

In addition to all of this we also have a few helper functions which are included for both view parsers. In order to start using these you can add them to their respective view parser as stated below:

Twig

$view->parserExtensions = array(
    new \Slim\Views\TwigExtension(),
);

Smarty

$view->parserExtensions = array(
    dirname(__FILE__) . '/vendor/slim/views/Slim/Views/SmartyPlugins',
);

These helpers are listed below.

  • urlFor
  • siteUrl
  • baseUrl
  • currentUrl

urlFor

Twig

Inside your Twig template you would write:

{{ urlFor('hello', {"name": "Josh", "age": "19"}) }}

You can easily pass variables that are objects or arrays by doing:

Hello {{ name }}">
Hello {{ name }}

If you need to specify the appname for the getInstance method in the urlFor functions, set it as the third parameter of the function in your template:

Hello {{ name }}">
Hello {{ name }}

Smarty

Inside your Smarty template you would write:

{urlFor name="hello" options="name.Josh|age.26"}

or with the new array syntax:

"Josh", "age" => "26"]}">
{urlFor name="hello" options=["name" => "Josh", "age" => "26"]}

You can easily pass variables that are arrays as normal or using the (.):

Hello {$name}">
Hello {$name}

If you need to specify the appname for the getInstance method in the urlFor functions, set the appname parameter in your function:

Hello {$name}">
Hello {$name}

siteUrl

Twig

Inside your Twig template you would write:

{{ siteUrl('/about/me') }}

Smarty

Inside your Smarty template you would write:

{siteUrl url='/about/me'}

baseUrl

Twig

Inside your Twig template you would write:

{{ baseUrl() }}

Smarty

Inside your Smarty template you would write:

{baseUrl}

currentUrl

Twig

Inside your Twig template you would write:

{{ currentUrl() }}

Smarty

Inside your Smarty template you would write:

{currentUrl}

Authors

Josh Lockhart

Andrew Smith

License

MIT Public License

Comments
  • templates.path

    templates.path

    Setting templates.path in the Slim configuration options doesn't set the path for the Twig view. This creates exceptions like: Uncaught exception 'Twig_Error_Loader' with message 'The "" directory does not exist.

    It should at least be documented that $view->setTemplatesDirectory(PATH_TO_DIRECTORY) needs to be called for this to work

    opened by robot-c0der 19
  • getData instead of all

    getData instead of all

    I do not find any function all in the slim code base and it seems getData works while all is not.

    let me know if it's a wrong patch. (Twig seems using all() too)

    Thanks

    opened by fayland 7
  • Twig dump function

    Twig dump function

    Hi I'm trying to use the dump function in a twig template but I get a "The function "dump" does not exist" error. I have the following parser options:

    'charset' => 'utf-8', 'auto_reload' => true, 'strict_variables' => false, 'autoescape' => true, 'debug'=>true

    Any suggestions would be greatfully recieved.

    opened by dgee2 5
  • Other templating

    Other templating

    I'm a little confused. If I want to use Mustache, would you accept a pull request to this repo or should I use the deprecated repo or am I supposed to use this, fork, write my own and not contribute back?

    I saw that you wanted it to be smaller, but wasn't clear if others wanted to use a different templating engine.

    Thanks again!!

    opened by fmitchell 5
  • Class 'Twig_Extension' not found

    Class 'Twig_Extension' not found

    Hello,

    I've a problem with Twig Extension :

        require 'vendor/autoload.php';
    
        $app = new \Slim\Slim(array(
            'debug' => true,
            'templates.path' => 'views/',
            'view' => new \Slim\Views\Twig(),
        ));
    
        $view = $app->view();
        $view->parserOptions = array(
            'debug' => true,
        );
        $view->parserExtensions = array(
            new \Slim\Views\TwigExtension()
        );
    
    
    
    
        $app->get('/hello/:name', function ($name) use ($app) {
            $app->render('hello.html.twig', array(
                'name' => $name,
            ));
        });
    
        $app->run();
    

    And the error : Fatal error: Class 'Twig_Extension' not found in ***\vendor\slim\views\TwigExtension.php on line 38

    Have you any ideas ?

    Thanks

    opened by babeuloula 3
  • Add support for Plates templating system.

    Add support for Plates templating system.

    This adds support for the Plates templating engine. The implementation is based around this one by @philipsharp (https://github.com/philipsharp/slim-view-plates), but with the addition of an extension to integrate the URL methods as well some documentation.

    Any thoughts would be appreciated. Cheers.

    opened by ziadoz 3
  • how to use {{ dump(var) }} with twig?

    how to use {{ dump(var) }} with twig?

    how to use {{ dump(var) }} with twig? since the last update v1.1.0 Twig extension, Debug is become impaired, what to do? :(

    https://github.com/fabpot/Twig-extensions/commit/c0ab818595338dd5569369bfce2552d02cec5d50

    index.php (Bootstrap)

    <?php
    define('ROOT', dirname(__DIR__));
    
    # Autoload
    $loader = require ROOT.'/vendor/autoload.php';
    // $loader->add('Lib', ROOT.'/lib/');
    // spl_autoload_register(function($class){
    //  $list = [
    //      ROOT.'/app/'.$class.'.php',
    //      ROOT.'/lib/'.$class.'.php',
    //      ROOT.'/lib/'.$class.'.class.php',
    //  ];
    //  foreach($list as $k => $v){if(file_exists($v)){
    //      include $v; return true;
    //  }}
    // });
    
    
    # Init Slim
    $app = new \SlimController\Slim([
        'mode'                       => 'production',
        'debug'                      => false,
        'view'                       => new \Slim\Views\Twig(),
        'templates.path'             => ROOT.'/templates',
        'cacheDirectory'             => ROOT.'/cache',
        'controller.class_prefix'    => '\\MyApp\\Controller',
        'controller.method_suffix'   => 'Action',
        'controller.template_suffix' => 'html.twig'
    ]);
    
    
    # Gestion de la configuration selon le mode
    if(\Lib\Func::env() == 'LOCAL') $app->config('mode', 'development');
    
    $app->configureMode('production', function() use ($app){
        $app->view->parserOptions    = ['cache' => $app->config('cacheDirectory')];
        $app->view->parserExtensions = [
            new \Slim\Views\TwigExtension()
        ];
    });
    $app->configureMode('development', function() use ($app){
        $app->config([
            'debug' => true
        ]);
        $app->view->parserOptions    = ['debug' => true];
        $app->view->parserExtensions = [
            new \Slim\Views\TwigExtension(),
            new \Twig_Extensions_Extension_Debug()
        ];
    });
    
    # Components
    
    $app->addRoutes([
        '/'            => 'Home:index',
    ]);
    
    // require_once ROOT.'/app/routes.php';
    
    $app->run();
    
    opened by Glaived 3
  • Fix declaration incompatibility with Slim\View

    Fix declaration incompatibility with Slim\View

    After this commit the Slim\Views\Twig::render() declaration is not compatible with the Slim\View::render()

    https://github.com/codeguy/Slim/commit/8e3b1fcc303eb9964c08a62404bc415ccb1189a6

    Strict Standards: Declaration of Slim\Views\Twig::render() should be compatible with Slim\View::render($template, $data = NULL) in /app/vendor/slim/views/Slim/Views/Twig.php on line 46

    opened by kachar 3
  • Support for Twig extensions?

    Support for Twig extensions?

    Maybe I'm missing something, but I don't see a way in the docs to do $twig->addExtension()

    After upgrading a project to slim-views from extras, I'm not able to use Twig's dump function because of this

    Is this functionality in the pipeline, or is it already there and I just need more coffee?

    opened by kieranajp 3
  • urlFor, baseUrl, siteUrl functions in twig do not exist.

    urlFor, baseUrl, siteUrl functions in twig do not exist.

    Type: Twig_Error_Syntax
    Message: The function "urlFor" does not exist in "views/base.html.twig" at line 28
    

    this is what i get when i try to use all thre functions.

    my composer.json:

    {
        "require" : {
            "slim/slim" : "2.*",
            "doctrine/orm" : "2.4.*@dev",
            "slim/views" : "0.1.*",
            "twig/twig" : "1.*"
        }
    }
    
    opened by NaGeL182 2
  • Support array-based options argument for Smarty function {urlFor}

    Support array-based options argument for Smarty function {urlFor}

    Smarty supports native PHP arrays as arguments for functions. I think the syntax in templates is much cleaner than the current 'dot'-solution. This PR is backwards compatible.

    Examples usages:

    {urlFor name="foo" options=["key" => "value"]}
    {urlFor name="foo" options=["key" => $value]}
    {urlFor name="foo" options=$options}
    
    opened by thijsw 2
  • Redirect not working

    Redirect not working

    Hi. I have a problem. Why does not it work redirect?

    $app = new \Slim\App();
    $app->get('/', function ($request, $response, $args) {
    return $response->withRedirect($this->router->pathFor('name'));//not work
    });
    
    $app->get('/auth/signup', function ($request, $response, $args) {
    return 'Hello';
    })->setName('name');
    
    $app -> run();
    

    or

    
    $app->get('/', function ($req, $res, $args) {
      return $res->withStatus(302)->withHeader('Location', '/auth/signup'); //Not work
    });
    

    Thanks!,

    opened by sharomet 1
  • Differences between baseUrl() and currentUrl()

    Differences between baseUrl() and currentUrl()

    What's the difference between baseUrl() and currentUrl() ? If I'm on the page http://www.iubar.it/index.php, how can I get the address http://www.iubar.it (wihout the page name) ??? Thank you in advance for any help

    Regards

    Andrea

    opened by borgogelli 0
  • Catches error thrown from Twig v 1.21 and newer

    Catches error thrown from Twig v 1.21 and newer

    Since Twig 1.21 (https://github.com/twigphp/Twig/commit/cc980282dee1964d867b70666ec7d2183d87ea4c) using Twig_Loaders is deprecated, and triggers a silent error using @ supressor. However, certain middlewares such as Whoops will still stop the normal flow.

    This PR wraps the Twig_Loader usage in a try/catch block, silently sending an eventual error to Slim's log. If the user's dependency has a Twig version prior to 1.21, it behaves just as usual.

    opened by ffflabs 1
  • Update to support new twig auto loading

    Update to support new twig auto loading

    the new version you get with composer require twig/twig changes he way autoloader works and deletes some classes so this slim views don't work any more with it.

    opened by tristanbailey 0
  • Only for technical curiosity. It's not an issue

    Only for technical curiosity. It's not an issue

    Hello

    I use your code with the Twig view. When I write:

    $this->app->render();
    $this->app->log->debug('Writing a log message after page rendering.');
    

    I could read the log message in the debug bar, while if I don't use your code, but the raw DebugBar code, the message is never showed.

    Why ?

    Thank you in advance

    Andrea

    opened by borgogelli 0
Releases(0.1.3)
  • 0.1.3(Dec 9, 2014)

  • 0.1.2(Apr 3, 2014)

  • 0.1.1(Dec 8, 2013)

  • 0.1.0(Jul 14, 2013)

    Release Notes

    This is the first release of the newly created Slim Views which takes the only two officially supported Views from the Slim-Extras repository.

    Below we will outline what has changed between this and the Slim-Extras Twig and Smarty view classes.

    Changelog

    • Methods and properties are no longer static (breaking change)
    • Method and property names are more consistent
      • getInstance()
      • parserExtensions
      • parserDirectory
    • Checking if Smarty class is available before including it
    • View helper extensions
    Source code(tar.gz)
    Source code(zip)
Owner
Slim Framework
Slim is a PHP micro framework that helps you quickly write simple yet powerful web applications and APIs.
Slim Framework
PSR Log - This repository holds all interfaces/classes/traits related to PSR-3.

PSR Log This repository holds all interfaces/classes/traits related to PSR-3. Note that this is not a logger of its own. It is merely an interface tha

PHP-FIG 10.1k Jan 3, 2023
FuelPHP v1.x is a simple, flexible, community driven PHP 5.3+ framework, based on the best ideas of other frameworks, with a fresh start! FuelPHP is fully PHP 7 compatible.

FuelPHP Version: 1.8.2 Website Release Documentation Release API browser Development branch Documentation Development branch API browser Support Forum

Fuel 1.5k Dec 28, 2022
Mind is the PHP code framework designed for developers. It offers a variety of solutions for creating design patterns, applications and code frameworks.

Mind Mind is the PHP code framework designed for developers. It offers a variety of solutions for creating design patterns, applications and code fram

null 0 Dec 13, 2021
Ergonode is modern PIM platform based on Symfony and Vue.js frameworks.

Modern Product Information Management Platform Ergonode is modern PIM platform based on Symfony and Vue.js frameworks. It has modular structure and gi

Ergonode 100 Dec 19, 2022
💡 Mudrock is a MVC PHP framework, which was inspired by the Laravel and CodeIgniter frameworks.

?? Mudrock is a MVC PHP framework, which was inspired by the Laravel and CodeIgniter frameworks

null 3 Nov 17, 2021
The package contains a bootstrap for running Yii3 web application.

Yii Web Runner The package contains a bootstrap for running Yii3 web application. Requirements PHP 8.0 or higher. Installation The package could be in

Yii Software 4 Oct 15, 2022
🚀 This is a utility library that contains tools you may use everywhere.

Utilities Someday I will write documentation for this library, but for now, you can use it and see how it works. Introduction Some documentation will

Utilities for PHP 6 Sep 16, 2022
This extension provides a view renderer for Pug templates for Yii framework 2.0 applications.

This extension provides a view renderer for Pug templates for Yii framework 2.0 applications.

Revin Roman 9 Jun 17, 2022
Slim Framework view helper built on top of the Twig templating component

Slim Framework Twig View This is a Slim Framework view helper built on top of the Twig templating component. You can use this component to create and

Slim Framework 321 Dec 16, 2022
Domain Driven Design PHP helper classes

carlosbuenosvinos/ddd This library will help you with typical DDD scenarios, for now: Application Services Interface Transactional Application Service

Domain-Driven Design in PHP 642 Dec 28, 2022
PHPneeds library (classes) package.

PHPneeds is a lightweight non-MVC PHP library for quickly start a project. About PHPneeds library (classes) package. Please use with PHPneeds base pro

PHPneeds 2 Oct 21, 2021
Provides database storage and retrieval of application settings, with a fallback to the config classes.

Provides database storage and retrieval of application settings, with a fallback to the config classes.

CodeIgniter 4 web framework 47 Dec 29, 2022
An asynchronous event driven PHP socket framework. Supports HTTP, Websocket, SSL and other custom protocols. PHP>=5.3.

Workerman What is it Workerman is an asynchronous event-driven PHP framework with high performance to build fast and scalable network applications. Wo

walkor 10.2k Dec 31, 2022
Implementing programming best practices and patterns, and creating a custom PHP framework from scratch.

Implementing programming best practices and patterns, and creating a custom PHP framework from scratch.

Sajidur Rahman 3 Jul 2, 2022
Rori-PHP is custom non production web application framework inspired by Laravel syntax

Rori-PHP is custom non production web application framework inspired by Laravel syntax. A web framework provides a structure and starting point for your application allowing you to focus on creating something amazing.

UnknownRori 5 Jul 28, 2022
Slim Framework custom views

Slim Views This repository contains custom View classes for the template frameworks listed below. You can use any of these custom View classes by eith

Slim Framework 302 Feb 21, 2022
Gracili is a PHP Application Template to quickly create a new Project

Gracili What is Gracili? Gracili is a PHP Application Template to quickly create a new Project. Using this template can save you a lot of time. With t

Björn Pfoster 1 May 12, 2021
Plates Template Integration for Slim micro framework 3

Plates Template Integration for Slim micro framework 3 Render your Slim 3 application views using Plates template engine. Install Via Composer $ compo

Projek XYZ 26 Feb 5, 2022
🍸A Slim Web Application Template

Gracili What is Gracili? Gracili is a PHP Application Template to quickly create a new Project. Using this template can save you a lot of time. With t

Björn Pfoster 1 May 12, 2021