Allows you to use Twig seamlessly in Laravel

Related tags

Laravel TwigBridge
Overview

Allows you to use Twig seamlessly in Laravel.

Latest Stable Version Total Downloads test License

Requirements

TwigBridge >= 0.13 supports Twig 3. If you need Twig 1/2 support, use the 0.12 versions.

Installation

Require this package with Composer

composer require rcrowe/twigbridge

Quick Start

Once Composer has installed or updated your packages you need to register TwigBridge with Laravel itself. Open up config/app.php and find the providers key, towards the end of the file, and add 'TwigBridge\ServiceProvider', to the end:

'providers' => [
     ...
                TwigBridge\ServiceProvider::class,
],

Now find the aliases key, again towards the end of the file, and add 'Twig' => 'TwigBridge\Facade\Twig', to have easier access to the TwigBridge (or Twig\Environment):

'aliases' => [
    ...
                'Twig' => TwigBridge\Facade\Twig::class,
],

Now that you have both of those lines added to config/app.php we will use Artisan to add the new twig config file:

php artisan vendor:publish --provider="TwigBridge\ServiceProvider"

At this point you can now begin using twig like you would any other view

//app/Http/routes.php
//twig template resources/views/hello.twig
Route::get('/', function () {
    return View::make('hello');
});

You can create the twig files in resources/views with the .twig file extension.

resources/views/hello.twig

Configuration

Once Composer has installed or updated your packages you need to register TwigBridge with Laravel itself. Open up config/app.php and find the providers key towards the bottom and add:

'TwigBridge\ServiceProvider',

You can add the TwigBridge Facade, to have easier access to the TwigBridge (or Twig\Environment).

'Twig' => 'TwigBridge\Facade\Twig',
Twig::addExtension('TwigBridge\Extension\Loader\Functions');
Twig::render('mytemplate', $data);

TwigBridge's configuration file can be extended in your ConfigServiceProvider, under the twigbridge key. You can find the default configuration file at vendor/rcrowe/twigbridge/config.

You should use Artisan to copy the default configuration file from the /vendor directory to /config/twigbridge.php with the following command:

php artisan vendor:publish --provider="TwigBridge\ServiceProvider"

If you make changes to the /config/twigbridge.php file you will most likely have to run the twig:clean Artisan command for the changes to take effect.

Installation on Lumen

For Lumen, you need to load the same Service Provider, but you have to disable the Auth, Translator and Url extensions in your local configuration. Copy the config/twigbridge.php file to your local config folder and register the configuration + Service Provider in bootstrap/app.php:

$app->configure('twigbridge');
$app->register('TwigBridge\ServiceProvider');

Usage

You call the Twig template like you would any other view:

// Without the file extension
View::make('i_am_twig', [...])

TwigBridge also supports views in other packages:

View::make('pagination::simple')

The above rules continue when extending another Twig template:

{% extends "parent" %}
{% extends "pagination::parent" %}

You can call functions with parameters:

{{ link_to_route('tasks.edit', 'Edit', task.id, {'class': 'btn btn-primary'}) }}

And output variables, escaped by default. Use the raw filter to skip escaping.

{{ some_var }}
{{ html_var | raw }}
{{ long_var | str_limit(50) }}

Extensions

Sometimes you want to extend / add new functions for use in Twig templates. Add to the enabled array in config/twigbridge.php a list of extensions for Twig to load.

'enabled' => array(
    'TwigBridge\Extensions\Example'
)

TwigBridge supports both a string or a closure as a callback, so for example you might implement the Assetic Twig extension as follows:

'enabled' => [
    function($app) {
        $factory = new Assetic\Factory\AssetFactory($app['path'].'/../some/path/');
        $factory->setDebug(false);
        // etc.....
        return new Assetic\Extension\Twig\AsseticExtension($factory);
    }
]

TwigBridge comes with the following extensions enabled by default:

  • Twig\Extension\DebugExtension
  • TwigBridge\Extension\Laravel\Auth
  • TwigBridge\Extension\Laravel\Config
  • TwigBridge\Extension\Laravel\Dump
  • TwigBridge\Extension\Laravel\Form
  • TwigBridge\Extension\Laravel\Gate
  • TwigBridge\Extension\Laravel\Html
  • TwigBridge\Extension\Laravel\Input
  • TwigBridge\Extension\Laravel\Session
  • TwigBridge\Extension\Laravel\String
  • TwigBridge\Extension\Laravel\Translator
  • TwigBridge\Extension\Laravel\Url
  • TwigBridge\Extension\Loader\Facades
  • TwigBridge\Extension\Loader\Filters
  • TwigBridge\Extension\Loader\Functions

To enable '0.5.x' style Facades, enable the Legacy Facades extension:

  • TwigBridge\Extension\Laravel\Legacy\Facades

FilterLoader and FunctionLoader

These loader extensions exposes Laravel helpers as both Twig functions and filters.

Check out the config/twigbridge.php file to see a list of defined function / filters. You can also add your own.

FacadeLoader

The FacadeLoader extension allows you to call any facade you have configured in config/twigbridge.php. This gives your Twig templates integration with any Laravel class as well as any other classes you alias.

To use the Laravel integration (or indeed any aliased class and method), just add your facades to the config and call them like URL.to(link) (instead of URL::to($link))

Functions/Filters/Variables

The following helpers/filters are added by the default Extensions. They are based on the helpers and/or facades, so should be self explaining.

Functions:

  • asset, action, url, route, secure_url, secure_asset
  • auth_check, auth_guest, auth_user
  • can
  • config_get, config_has
  • dump
  • form_* (All the Form::* methods, snake_cased)
  • html_* (All the Html::* methods, snake_cased)
  • input_get, input_old, input_has
  • link_to, link_to_asset, link_to_route, link_to_action
  • session_has, session_get, csrf_token, csrf_field, method_field
  • str_* (All the Str::* methods, snake_cased)
  • trans, trans_choice
  • url_* (All the URL::* methods, snake_cased)

Filters:

  • camel_case, snake_case, studly_case
  • str_* (All the Str::* methods, snake_cased)
  • trans, trans_choice

Global variables:

  • app: the Illuminate\Foundation\Application object
  • errors: The $errors MessageBag from the Validator (always available)

Artisan Commands

TwigBridge offers a command for CLI Interaction.

Empty the Twig cache:

$ php artisan twig:clean

Lint all Twig templates:

$ php artisan twig:lint
Comments
  • Mark a function as escaped

    Mark a function as escaped

    It would be nice if there was a way to mark a function as escaped in the configuration, rather than appending |raw throughout templates. It seems that the Twig way to do this is:

    new Twig_Function_Function('nav_link', ['is_safe' => ['html']])
    

    It seems that a way to do this could be allowing config.functions to accept Twig_Function_Function instances?

    opened by rmasters 41
  • Version 0.6.0

    Version 0.6.0

    TwigBridge has grown and become more important while at the same time I've grown unhappy with how some parts of the library and hope to fix this with the next release.

    So lets open things for discussion and get the ball rolling.

    • [x] Improve the Twig syntax for calling aliases (#61)
    • [x] Improve template loading (#39, #60)
    • [ ] Actually get the twig:compile working (#41)
    • [x] Make better use of the IoC (#56)
    • [x] Improve Laravel composer / creator support (#59, #66)
    • [ ] Improve tests & coverage
    • [x] Review getAttributes function
    • [ ] Improved package support (#74)
    • [x] Render string templates (#94)
    • [ ] Decide which functions / filters are escaped by Laravel extensions

    @barryvdh @ivannpaz

    opened by rcrowe 39
  • Version 0.6

    Version 0.6

    • [x] Improve the Twig syntax for calling aliases (#61)
    • [x] Improve template loading (#39, #60)
    • [x] ~~Actually get the twig:compile working (#41)~~ php artisan optimize now does this
    • [x] Twig engine should extend CompilerEngine
    • [x] Make better use of the IoC (#56, #119)
    • [x] Improve Laravel composer / creator support (#59, #66)
    • [ ] Improve tests & coverage
    • [x] Review getAttributes Template method (#126)
    • [ ] ~~Improved package support (#74)~~ to be confirmed
    • [x] Render string templates (#94)
    • [x] Decide which functions / filters are escaped by Laravel extensions (#68)
    • [x] Improve error handling (#115)
    opened by rcrowe 37
  • Exception if Eloquent record field is Null

    Exception if Eloquent record field is Null

    I've an Eloquent record like this :

    object(Cms\Page\Page)#308 (18) {
      ["table":protected]=>
      string(9) "cms_pages"
      ["pageStatus":protected]=>
      array(2) {
        [0]=>
        string(7) "visible"
        [1]=>
        string(6) "hidden"
      }
      ["pageTypes":protected]=>
      array(4) {
        [0]=>
        string(3) "std"
        [1]=>
        string(4) "prod"
        [2]=>
        string(4) "blog"
        [3]=>
        string(4) "news"
      }
      ["sequence"]=>
      bool(false)
      ["connection":protected]=>
      NULL
      ["primaryKey":protected]=>
      string(2) "id"
      ["perPage":protected]=>
      int(15)
      ["incrementing"]=>
      bool(true)
      ["timestamps"]=>
      bool(true)
      ["attributes":protected]=>
      array(13) {
        ["id"]=>
        string(1) "2"
        ["parent_id"]=>
        NULL
        ["type"]=>
        string(3) "std"
        ["name"]=>
        string(9) "Chi siamo"
        ["image"]=>
        NULL
        ["gallery"]=>
        NULL
        ["redirect"]=>
        NULL
        ["status"]=>
        string(0) ""
        ["visible_from"]=>
        NULL
        ["visible_to"]=>
        NULL
        ["sequence"]=>
        string(3) "0.0"
        ["created_at"]=>
        string(19) "2013-01-31 18:20:23"
        ["updated_at"]=>
        string(19) "2013-01-31 18:20:23"
      }
    }
    

    If I try to retrieve an item of this record in a Twig view all works fine : {{ page.name }} => 'Chi siamo'

    but if the field is NULL I've get an exception :

    Twig_Error_Runtime: An exception has been thrown during the rendering of a template ("Warning: call_user_func_array() expects parameter 1 to be a valid callback, class 'Illuminate\Database\Query\Builder' does not have a method 'gallery' in /Applications/MAMP/htdocs/git/davide/selfcomposer-3-laravel/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php line 445") in "content_form.html" at line 4.
    
    opened by billmn 21
  • feature request: view composers

    feature request: view composers

    One cool thing Laravel has is view composers -- a way to say "any time you use this view, pass it this data." I'm wondering if there's any way to do this with includes in Twigbridge. I fiddled around and couldn't figure anything out, but if you can, you will make me very happy.

    opened by jtgrimes 20
  • Feature - Expose Functions (calling laravel 4 helpers methods in view)

    Feature - Expose Functions (calling laravel 4 helpers methods in view)

    Regarding: https://github.com/rcrowe/TwigBridge/issues/42

    This allows the user to specify functions (for instance laravel helpers) that should be made available to the Twig Views.

    'functions' => array(
        'base_path',
        'app_path',
        'camel_case',
    )
    

    This configuration would make these three functions available to the views as:

    {{ base_path() }}
    {{ app_path() }}
    {{ camel_case("snake_case_incoming") }}
    

    Also possible to specify a Closure callback directly:

    'functions' => array(
        'bond' => function($name, $lastname) {
            return "My name is {$lastname}, {$name} {$lastname}...";
        },
    )
    

    And later in the view:

    {{ bond("Rob", "Crowe") }}
    

    For a dramatic "My name is Crowe, Rob Crowe...".

    opened by ivannpaz 18
  • Closes #388 [2]

    Closes #388 [2]

    Remake of https://github.com/rcrowe/TwigBridge/pull/398 which was reverted due to https://github.com/rcrowe/TwigBridge/pull/398#issuecomment-653434596

    Before we were use checking for calls against Eloquent models. #388 is lack of sandbox checks on Container objects.

    The problem with the old PR was that it was checking ArrayAccess but using $object->$item - see https://github.com/rcrowe/TwigBridge/pull/398#issuecomment-653512286

    This PR resolves that issue by using $object[$item] and also adds the isset() check which happens in the upstream code - https://github.com/twigphp/Twig/blob/3.x/src/Extension/CoreExtension.php#L1370

    opened by bytestream 16
  • fixed #126 relation querying in 0.6

    fixed #126 relation querying in 0.6

    #126 fixed resolving of attributes in templates concerning eloquent models and specifically their relations, whereas loading as method loads an querybuilder and loading as property loads a collection

    opened by luceos 16
  • 0.6-beta2 - getXAttribute undefined offset N

    0.6-beta2 - getXAttribute undefined offset N

    While attempting to use the twigbridge 0.6-beta2 in laravel I came across the issue that the template did not resolve the attribute. It currently provides the error

    An exception has been thrown during the rendering of a template ("Undefined offset: 44395496") in "packages/<vendor>/<package>/<subdir>/emailaddresses" at line 5.
    

    This error occurs while request the getAddressAttribute from the emailAddress model. And thrown on: vendor/twig/twig/lib/Twig/Template.php:148

    Any idea why this occurs? When using the complete getAddressAttribute, no exception is thrown.

    opened by luceos 15
  • [0.7] Update for Laravel 5.x

    [0.7] Update for Laravel 5.x

    Changes:

    • [x] Update constraints
    • [x] New config system (no namespaces, load manually, move out src folder)
    • [x] Html + Form are not included by default
    • [ ] Fix the tests
    • [ ] More changes?
    opened by barryvdh 14
  • Question: database loader

    Question: database loader

    Thanks for the great package. My app uses developer contributed themes that I need to store in the database for scalability and other reasons, as opposed to the file system. I've had a database loader working OK with standalone twig, but I'm struggling to see where to start with TwigBridge, however I'd like to use it to make use of Laravel View type functionality such as View Composers etc. Any suggestions for how to add a database loader would be greatly appreciated?

    opened by ghost 14
  • Fix: Facade Caller is never safe if the result is an object

    Fix: Facade Caller is never safe if the result is an object

    This PR addresses an issue we were experiencing with Facades. We're upgrading an old project from Laravel 5.5 to 9.x that utilizes a few facades to generate code, specifically Laravel Collective's Form Builder. If you run this:

    {{ Form.open() }}
    

    it will autoescape the tag. This had previously not escaped the HTML for years on older releases, producing forms as expected.

    I did a few hours of troubleshooting and determined the cause was this line: https://github.com/rcrowe/TwigBridge/blob/f4968efb99537cc1b37c5bf20280614aadc31825/src/Extension/Loader/Facade/Caller.php#L89

    Form.open() returns an HtmlString object which has a __toString() method. The expectation is it would use that method to convert it to a String, but that doesn't happen because is_callable($result) should never return true on an object. Instead, it is intended to be run as:

    is_callable([$result, '__toString']);
    

    Unfortunately, switching this one line to just use that instead of the combined is_callable() && method_exists() resulted in some unexpected behavior. The commit that added this check said it was to fix a PHP 8 TypeError, and my change to usuing is_object() instead of is_callable() should satisfy the type errors, fix the bugs we're seeing, and maintain expected behavior.

    opened by jjanusch 0
  • Not working in Lumen

    Not working in Lumen

    I followed the instructions to add the package to lumen, but I get the following error:

    Call to undefined function TwigBridge\Node\resolve()

    In the file: /src/Node/EventNode.php on line 32, the function resolve() is called, but it is undefined.

    opened by burgoyn1 0
  • How to use twigphp/cache-extra?

    How to use twigphp/cache-extra?

    Hey, I am trying to use the twigphp/cache-extra (https://twig.symfony.com/doc/3.x/tags/cache.html) extension in TwigBridge.

    In app/config/twigbridge.php I added in extensions->enabled section an entry:

    TwigExtraCacheExtension::class,
    

    When I try to use the cache block, I get an error:

    ErrorException (E_ERROR)
    Unable to load the "Twig\Extra\Cache\CacheRuntime" runtime.
    

    The twig documentation says:

    If you are not using Symfony, you must also register the extension runtime:
    
    use Symfony\Component\Cache\Adapter\FilesystemAdapter;
    use Symfony\Component\Cache\Adapter\TagAwareAdapter;
    use Twig\Extra\Cache\CacheRuntime;
    use Twig\RuntimeLoader\RuntimeLoaderInterface;
    
    $twig->addRuntimeLoader(new class implements RuntimeLoaderInterface {
        public function load($class) {
            if (CacheRuntime::class === $class) {
                return new CacheRuntime(new TagAwareAdapter(new FilesystemAdapter()));
            }
        }
    });
    

    However, I have no idea where in the application to add such a loader. From what I see, extensions are added in this file: vendor/barryvdh/laravel-form-bridge/src/ServiceProvider.php

    Does this mean I should overwrite this service provider and use a custom one?

    opened by event15 2
  • trans node is missing?

    trans node is missing?

    Hi, regarding #18 I want to add the {% trans %} tag but the mentioned issue was from 2013 and it is not working right now. I'm using Laravel 8 with the following packages:

    "rcrowe/twigbridge": "^0.12.3",
    "twig/twig": "^3.3"
    

    And if I add the twig extensions package, it happens the following:

    Using version ^1.5 for twig/extensions
    ./composer.json has been updated
    Updating dependencies (including require-dev)
    Your requirements could not be resolved to an installable set of packages.
    
      Problem 1
        - Conclusion: don't install twig/extensions v1.5.4
        - Conclusion: don't install twig/extensions v1.5.3
        - Conclusion: don't install twig/extensions v1.5.2
        - Conclusion: don't install twig/extensions v1.5.1
        - Conclusion: don't install twig/extensions v1.5.0
        - Conclusion: remove twig/twig v3.3.0
        - Installation request for twig/extensions ^1.5 -> satisfiable by twig/extensions[1.x-dev, v1.5.0, v1.5.1, v1.5.2, v1.5.3, v1.5.4].
        - Conclusion: don't install twig/twig v3.3.0
        - twig/extensions 1.x-dev requires twig/twig ^1.27|^2.0 -> satisfiable by twig/twig[1.x-dev, 2.x-dev].
        - Can only install one of: twig/twig[1.x-dev, v3.3.0].
        - Can only install one of: twig/twig[2.x-dev, v3.3.0].
        - Installation request for twig/twig (locked at v3.3.0, required as ^3.3) -> satisfiable by twig/twig[v3.3.0].
    
    
    Installation failed, reverting ./composer.json to its original content.
    

    So, is there any solution so that I can add the {% trans %} tag to twig using Laravel 8?

    Thanks in advance.

    opened by didix16 0
  • [Question] Laravel8 + TwigBridge + GraphQL Twig extension -- example or available package?

    [Question] Laravel8 + TwigBridge + GraphQL Twig extension -- example or available package?

    I'm looking to inject php GraphQL query results , with queries defined in Twig(Bridge) templates, using Twig Extension in Laravel8

    I've asked here,

    https://stackoverflow.com/questions/66665429/how-to-inject-php-graphql-query-results-with-queries-defined-in-twigbridge-t

    but don't expect bumping into someone using the combination there; more likely here.

    Anyone have / know of an existing Laravel+TwigBridge+GraphQL Twig extension ?

    opened by huna02 0
  • store templates in database

    store templates in database

    I have a question.

    Is it posible to store template/view files in a database with TwigBride?

    I want to run multiple domains on one codebase with twig templates in sandboxmode. for easy editing I want to put the templates in a database.

    opened by tomadmiraal 1
Releases(v0.14.0)
Owner
Rob Crowe
Rob Crowe
Twig-lint - Standalone twig linter

twig-lint - Standalone twig linter twig-lint is a lint tool for your twig files. It can be useful to integrate in your ci setup or as the basis of edi

Alexander 118 Dec 21, 2022
A Laravel package that allows you to use multiple ".env" files in a precedent manner. Use ".env" files per domain (multi-tentant)!

Laravel Multi ENVs Use multiple .envs files and have a chain of precedence for the environment variables in these different .envs files. Use the .env

Allyson Silva 48 Dec 29, 2022
If you are beginner in WordPress plugin development or if you want to develop your own store product plugin you use this plugin

hirwa-products-plugin If you are beginner in WordPress plugin development or if you want to develop your own store product plugin you use this plugin

NIYIBIZI HIRWA 1 Aug 23, 2022
Blade Snip allows you to use parts of a blade template multiple times. Basically partials, but inline.

Blade Snip Blade Snip allows you to use parts of a blade template multiple times. Basically partials, but inline: <div class="products"> @snip('pr

Jack Sleight 18 Dec 4, 2022
Give the power of Twig to Laravel

Allows you to use Twig seamlessly in Laravel. Requirements TwigBridge >= 0.13 supports Twig 3. If you need Twig 1/2 support, use the 0.12 versions. In

Rob Crowe 866 Jan 30, 2022
Twig-based PatternEngine for Pattern Lab.

Twig PatternEngine for Pattern Lab The Twig PatternEngine allows you to use Twig as the template language for Pattern Lab PHP. Once the PatternEngine

Pattern Lab 77 Oct 27, 2022
Laravel Impersonate is a plugin that allows you to authenticate as your users.

Laravel Impersonate Laravel Impersonate makes it easy to authenticate as your users. Add a simple trait to your user model and impersonate as one of y

404lab 1.6k Dec 30, 2022
A simple Content Moderation System for Laravel 5.* that allows you to Approve or Reject resources like posts, comments, users, etc.

Laravel Moderation A simple Moderation System for Laravel 5.* that allows you to Approve or Reject resources like posts, comments, users, etc. Keep yo

Alex Kyriakidis 509 Dec 30, 2022
This package allows you to easily track your laravel jobs!

Trackable Jobs For Laravel This package allows you to track your laravel jobs! Using this package, you can easily persist the output and the status of

Mateus Junges 220 Dec 25, 2022
Collection of the Laravel/Eloquent Model classes that allows you to get data directly from a Magento 2 database.

Laragento LAravel MAgento Micro services Magento 2 has legacy code based on abandoned Zend Framework 1 with really ugly ORM on top of outdated Zend_DB

Egor Shitikov 87 Nov 26, 2022
The missing laravel helper that allows you to inspect your eloquent queries with it's bind parameters

Laravel Query Inspector The missing laravel helper that allows you to ispect your eloquent queries with it's bind parameters Motivations Let's say you

Mouad ZIANI 59 Sep 25, 2022
Save Model is a Laravel package that allows you to save data in the database in a new way.

Save Model is a Laravel package that allows you to save data in the database in a new way. No need to worry about $guarded and $fillable properties in the model anymore. Just relax an use Save Model package.

Laratips 27 Mar 2, 2022
This package provides a Logs page that allows you to view your Laravel log files in a simple UI

A simplistics log viewer for your Filament apps. This package provides a Logs page that allows you to view your Laravel log files in a simple UI. Inst

Ryan Chandler 9 Sep 17, 2022
This package allows you to easily work with NanoID in your Laravel models.

Laravel Model UUIDs Introduction Huge thanks to Micheal Dyrynda, whose work inspired me to create this package based on laravel-model-nanoid but uses

Parables Boltnoel 3 Jul 27, 2022
A Laravel package that allows you to validate your config values and environment.

Table of Contents Overview Installation Requirements Install the Package Publishing the Default Rulesets Usage Creating a Validation Ruleset Using the

Ash Allen 152 Dec 15, 2022
This Laravel Nova package allows you to manage media and media fields

Nova Media Hub This Laravel Nova package allows you to manage media and media fields. Requirements php: >=8.0 laravel/nova: ^4.0 Features Media Hub UI

outl1ne 25 Dec 22, 2022
States allows you to create PHP classes following the State Pattern in PHP.

States allows you to create PHP classes following the State Pattern in PHP. This can be a cleaner way for an object to change its behavior at runtime without resorting to large monolithic conditional statements and this improve maintainability and workflows writing.

Teknoo Software 10 Nov 20, 2022
The query filter bundle allows you to filter data from QueryBuilder and the Database.

The query filter bundle allows you to filter data from QueryBuilder and the Database. you can filter multiple columns at the same time and also you can filter relation fields with two-level deep and without any join in your query builder.

Bugloos 15 Dec 29, 2022
This package allows you to render livewire components like a blade component, giving it attributes, slots etc

X-livewire This package allows you to render livewire components like a blade component, giving it attributes, slots etc. Assuming you wanted to creat

null 7 Nov 15, 2022