Slim Framework custom views

Related tags

Laravel Slim-Views
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

<?php
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

<?php
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:

<a href="{{ urlFor('hello', {"name": person.name, "age": person.age}) }}">Hello {{ name }}</a>

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:

<a href="{{ urlFor('hello', {"name": person.name, "age": person.age}, 'admin') }}">Hello {{ name }}</a>

Smarty

Inside your Smarty template you would write:

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

or with the new array syntax:

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

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

<a href="{urlFor name="hello" options="name.{$person.name}|age.{$person.age}"}">Hello {$name}</a>

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

<a href="{urlFor name="hello" appname="admin" options="name.{$person.name}|age.{$person.age}"}">Hello {$name}</a>

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
A package to easily make use of Iconic icons in your Laravel Blade views.

Blade Iconic A package to easily make use of Iconic icons in your Laravel Blade views. For a full list of available icons see the SVG directory. Iconi

Malik Alleyne-Jones 17 Aug 25, 2022
A package to easily make use of Simple Icons in your Laravel Blade views.

Blade Simple Icons A package to easily make use of Simple Icons in your Laravel Blade views. For a full list of available icons see the SVG directory.

UB Labs 12 Jan 17, 2022
🧑‍🔬 The missing assertions for your views in your Laravel applications.

Laravel View Assertions The missing assertions for your views in your Laravel applications. Installation You'll have to follow a couple of simple step

Sven Luijten 4 Dec 21, 2022
A package that uses blade templates to control how markdown is converted to HTML inside Laravel, as well as providing support for markdown files to Laravel views.

Install Install via composer. $ composer require olliecodes/laravel-etched-blade Once installed you'll want to publish the config. $ php artisan vendo

Ollie Codes 19 Jul 5, 2021
Cagilo - a set of simple components for use in your views Laravel Blade.

Cagilo - a set of simple components for use in your views Laravel Blade. Official Documentation Documentation for Cagilo can be found on its we

Cagilo 151 Dec 6, 2022
Create Laravel views (blade template) using 'php artisan' command-line interface

About LaraBit Have you ever wonder to create Laravel views (Blade Templates) using the same type of artisan commands that you usually use to create ne

Ragib MRB 5 Oct 15, 2021
Stash view is a composer package for Laravel which caches views using Russian Doll Caching methodology.

Stash View Stash view is a composer package for Laravel which caches views using Russian Doll Caching methodology. What is Russian Doll Caching ? It i

Bhushan Gaikwad 18 Nov 20, 2022
Take a look into your Laravel views

Xray - Take a look into your Laravel views When your Laravel project grows, so do the Laravel views. Sometimes it might be hard to figure out, which p

Beyond Code 572 Aug 6, 2022
A package to easily make use of SVG icons in your Laravel Blade views.

Blade Icons A package to easily make use of SVG icons in your Laravel Blade views. Originally "Blade SVG" by Adam Wathan. Turn... <!-- camera.svg -->

Blade UI Kit 1.7k Jan 2, 2023
Blade UI Kit is a set of renderless components to utilise in your Laravel Blade views

Blade UI Kit is a set of renderless components to utilise in your Laravel Blade views. In all essence, it's a collection of useful utilities, connecting the dots between different parts of the TALL stack. It was made for Blade, Laravel's powerful templating engine.

Blade UI Kit 1.2k Jan 5, 2023
Easily add a full Laravel blog (with built in admin panel and public views) to your laravel project with this simple package.

Webdevetc BlogEtc - Complete Laravel Blog Package Quickly add a blog with admin panel to your existing Laravel project. It has everything included (ro

WebDevEtc. 227 Dec 25, 2022
A package to easily make use of Iconsax in your Laravel Blade views.

Blade Iconsax A package to easily make use of Iconsax in your Laravel Blade views. This package contains 1.000 icons in 6 diferent styles, a total of

Guilherme Saade 4 Oct 22, 2022
Blade is a simple, yet powerful templating engine provided for the Slim Framework

slim-blade Blade is the default template engine of Laravel. The main advantage of Blade is template inheritance whilst using plain PHP. This package a

Kevin Darren 32 May 24, 2021
A Simple PHP Renderer for Slim 3 (or any other PSR-7 project)

PHP Renderer This is a renderer for rendering PHP view scripts into a PSR-7 Response object. It works well with Slim Framework 4. Cross-site scripting

Slim Framework 235 Jan 5, 2023
Slim Jam is a demo application to provide examples for composer package, PHPSpreadsheet, Shopify API etc. usages.

SLIM JAM Slim Jam is a demo application to provide examples for composer package, PHPSpreadsheet, Shopify API etc. usages. This project aims to take a

Uğur ARICI 2 Jan 9, 2022
🖼️ Laravel Nova Field for uploading and cropping images using Slim Image Cropper

??️ Laravel Nova Field for uploading and cropping images using Slim Image Cropper

Marius 5 Apr 2, 2022
Service manager for Slim compatible with Laravel packages

SlimServices SlimServices is a service manager for the Slim PHP microframework based on Laravel 4 service providers and DI container, allowing you to

its 76 Jul 23, 2022
cybercog 996 Dec 28, 2022
Generate and autoload custom Helpers, Builder Scope, Service class, Trait

laravel-make-extender Generate and autoload custom helpers, It can generate multilevel helpers in the context of the directory. Generate Service class

Limewell 30 Dec 24, 2022