Giter VIP home page Giter VIP logo

twigbridge's Introduction

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

Laravel automatically registers the Service Provider. Use Artisan to publish the 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

twigbridge's People

Contributors

acutting1755 avatar anahkiasen avatar angeljqv avatar astoltz avatar barryvdh avatar brunogaspar avatar bytestream avatar causamortis avatar damarev avatar filcius avatar grahamcampbell avatar itsgoingd avatar jn-jones avatar jwpage avatar kblais avatar lbausch avatar markhuot avatar mbardelmeijer avatar merlinus1 avatar mikevrind avatar misterdesign avatar nils-werner avatar rikh42 avatar scif avatar silverqx avatar sinius15 avatar steveneaston avatar svennis94 avatar timrspratt avatar winglian avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

twigbridge's Issues

Facades as globals?

Maybe it is just personal preference, but I don't really like the fallback facade_method() call. What do you think about adding Facades as globals?

So Config.get('key') instead of config_get('key'). This make it more clear that you are calling a Facade and not a 'real' function, and you can have more control over which facades you want to include.

I did some tests with two methods:

  1. Get the facade root and add that to the globals (https://github.com/barryvdh/laravel-twigbridge/blob/c3203b64e0f3742b9590e6dcb05f49f1cd5ca452/src/Barryvdh/TwigBridge/Extension/FacadeExtension.php)
  2. Create a 'fake' class that remembers the name and calls the function dynamic:
    https://github.com/barryvdh/laravel-twigbridge/blob/635e5d8fb0049996723910fc217f2993e4cf3d5c/src/Barryvdh/TwigBridge/Extension/FacadeExtension.php

The first is probably a bit 'cleaner', but the second is more flexible and call also call models (ie. User.first().email)

(And it could also be a possibility to add the 'app' container to the globals, so the IoC container can be used, but that is already possibly by adding it to the globals in the config I guess.)

Any thoughts?

unable to load custom extension

Hi,

I created an extension and registered it in 'extensions' => array and put it inside the app folder. Then I got:

FatalErrorException: Error: Class 'Twig_Extensions_Extension_Trans' not found in /Users/abbasadel/Documents/projects/hadanty7/vendor/rcrowe/twigbridge/src/TwigBridge/TwigBridge.php line 197

I put the class inside vendor/rcrowe/twigbridge/src/TwigBridge/Extensions/ and it worked.

My extension:

class Twig_Extensions_Extension_Trans extends Twig_Extension
{

    public function getFilters()
    {
        return array(
            'trans' => new Twig_Filter_Function('trans'),
        );
    }


    public function getName()
    {
        return 'i18n';
    }
}

Is is possible to create extension outside TwigBridge/Extensions folder?

Thanks
Abbas

Using chained functions through AliasLoader

Hi,

I trying to use the Laravel Notifications package (https://github.com/edvinaskrucas/notification) with TwigBridge.

Using the AliasLoader I was able to call the function,

{{ Notification::showAll() }}

using,

{{ Notification_showAll() }}

which is great but when I try to call,

{{ Notification_container('view')->showAll() }}

I get an error like,

Unexpected token "operator" of value ">" in "./layouts/people.twig" at line 21

Is there some other syntax I need to use for the alias loader for chained methods?

Thanks,

Felix

Problem With Stylesheet Link

I use Symfony2 and I use twig engine but I have problem with CSS links.
My CSS link doesn't work at all.
Please help me.

Accessing NULL properties of an Eloquent model in the template throws an error

I'm having a problem which sounds very much like the one outlined in issue #11 (which was closed a little while ago). Basically if I try to access a property of an eloquent model in the template I see a Twig_Error_Runtime error thrown. For instance, accessing this a property like this (which returns NULL)

{{ organiser.website }}

results in:

An exception has been thrown during the rendering of a template ("Call to undefined method Illuminate\Database\Query\Builder::website()") in "example.twig" at line 10.

Any thoughts on this? It sounds like the previous bug was squashed so not sure if this has crept back in again somehow or if this is a differnt issue under the hood.

Anything I can do to help figure it out please let me know! This is with the latest (0.2.6) version.

Feature request: calling a chained method

Re,

It'd be great if we could also call a chained method. For instance:

Former::checkboxes('level')
->checkboxes(0, 1, 2)
->check(array('level_0' => true, 'level_1' => false, 'level_2' => true))

Cheers.

Problem with URL::action and namespaces

I'm not sure whether this is a Twig or TwigBridge issue but, the following code :

<a href="{{ url_action('Api\UsersController@follow', user.id) }}">Follow</a>

Will cause an Exception, because it will compile to ApiUsersController for some reason, to make it work a double backslash is needed :

<a href="{{ url_action('Api\\UsersController@follow', user.id) }}">Follow</a>

Is this normal or ?

Add custom tests

I wanted to add a custom test to Twig but I can't seem to find how as when I do $app['twig']->addTest() I get a Unable to add test "mytest" as extensions have already been initialized..

Is there any way to extend Twig that way with the current implemenation ?

Force resolve of packages view

Take for instance you use a package that has its own views and would like to override a main layout view with your own (to add more navigation links, etc). The package view uses blocks in the view to allow overriding.

To override the packages view in Laravel, you have the following structure in your app:

Package structure:

/views
    /layouts
       admin.twig

admin.twig contains for instance:

{% block main_navigation %}
     Link 1
     Link 2
{% endblock %}

Your main app structure:

/app
    /views
        /packages
            /vendor
                /package_name
                    /layouts
                        admin.twig

admin.twig contains:

{% extends 'package_name::layouts.admin' %}
{% block main_navigation %}
     {{ parent() }}
     Link 3
{% endblock %}

When rendering the view, it will render the above however the extend in this instance will cause an endless loop as it will continue to resolve package_name::layouts.admin to the /app/views/packages/vendor/package_name

My question is, is there anyway to 'force' it to resolve the packages view? If not, maybe it would be worthwhile adding a prefix to force a resolve? i.e use > to represent always resolve the packages view?

 {% extends '>package_name::layouts.admin' %}

What about official twig extensions?

Hello!

I want to re-use existing templates but these templates need the official twig extensions, e.g. "{% trans "something to translate" %}". How can I activate these in the twig bridge?

Greetings
Carsten

Hard coded pagination path

in \twigbridge\src\TwigBridge\TwigServiceProivder, on line 26 you have the line

$this->app['view']->addNamespace('pagination', '/Users/rcrowe/Documents/Projects/flags/vendor/illuminate/pagination/src/Illuminate/Pagination/views');

I just commented it out to so I could play around some more, but I'm guessing that this line needs to be updated.

Form::open doesnt work

Hello,

I am trying to execute the following:

{% block content %}
{{ form_open(array("url" => "foo/bar", "method" => "post")) }}
    {{ form_label("Username", "username") }}
    {{ form_text("username") }}
    {{ form_label("Password", "password") }}
    {{ form_password("password") }}
{{ form_close() }}
{% endblock %}

I am using the Laravel Form:: helper (http://four.laravel.com/docs/html). It all works great except for the Form::open() call which as per the docs takes an array. However Twig bombs out with A parameter name must be a string, "Twig_Node_Expression_Constant" given in "login.twig"

How can I make TwigBridge work with methods that take an array as a parameter?

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.

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

@barryvdh @ivannpaz

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?

Command twig:compile exception (View not found)

When trying to precompile the twig templates:

$ php artisan twig:compile

The process breaks with:

[InvalidArgumentException]        
View [home/main.html] not found.

Extra info:

  • The twig views follow the"$viewname.html.twig" convention
  • The config.php for the TwigBridge specifies the extension as: 'extension' => 'html.twig'
  • The views load perfectly fine on site, this issue only happens with the compile command.

[Bug] Problem with alias loader

I've tried to call {{ str_starts_with() }} but now I've :

An exception has been thrown during the rendering of a template ("Method starts_with does not exist ...

I notice that you have removed "Str::camel()" from AliasLoader::getFunction method ... a very fast fix that I have tried is this :

list($class, $method) = $parts;
$class = strtolower($class);
$method = Str::camel($method);

Function rendered as HtmlEntities since Laravel 4.0.7 update

Since I update Laravel to 4.0.7 version, form function suddenly rendered as html entities

{{ Form_open({'url': '/login','class':'form-search row-fluid'}) }}
rendered as
&lt;form method=&quot;POST&quot; action=&quot;http://local.dev/login&quot; accept-charset=&quot;UTF-8&quot; class=&quot;form-search row-fluid&quot;&gt;

So then, now I have to use a "raw" filter to be rendered as HTML
{{ Form_open({'url': '/login','class':'form-search row-fluid'})|raw }}

I've used a lot of this function on my template, How not to use the raw filter in every function?

form_open (Form::Open) with arguments

Trying to insert an open form tag, like one below, in a twig template on laravel4:

create.twig:
{{ form_open(array('action' => 'FilmeController@postUpdate')) }}

{{ form_close() }}

And an exception is throwed:
Twig_Error_Syntax
A parameter name must be a string, "Twig_Node_Expression_Constant" given in "filme.create" at line 1

Seems that any Facade only accepts string as arguments. Any other type throw the exception above.

Thanks

AliasLoader doesn't handle methods with snake case

I'm trying to use anahkiasen/former in my Laravel 4 project.

I need to use some magic methods like these:

Former::horizontal_open();
Former::inline_checkboxes();

I'm trying to call them in my Twig template with:

{{ former_horizontal_open() }}
{{ former_inline_checkboxes() }}

However, the automatic conversion seems to change everything after the first _ to camelCase.

With leads to calling..

Former::horizontalOpen();
Former::inlineCheckboxes();

...which leads to undesirable results with Former, or any other package using snake case methods.

There needs to be a way to specify leaving the underscores alone. An alternative character or something, like how we use periods instead of -> to chain methods.

Input::old or input_old

Hi,

I cannot a find a way how i can print the old inputs.
In the controller I redirect the request to route with ->withInputs();

Redirect::route('auth.register')
            ->with('errors', $validator->getErrors())
            ->withInput();

and in the template I am trying to get the content of the input but it doesn't print anything.

{{ input_old('username') }}

i will appreciate your help or advice

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.

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.

Template inheritance problem.

Hello,

This is more a usage bug than a structural one. However I could not find a solution anywhere else.

Problem:

When attempting to extend a template with:

{% extends "base.twig" %}
{%block title%}My Title{%endblock%}

I get the following error:

Twig_Error_Loader
Unable to find template "base.twig" (looked into: C:\wamp\www\devaidv4\app\config/../views, C:\wamp\www\devaidv4\app\config/../views).

The 'base.twig' file is located in '../app/views/base.twig'
The child template in '../app/views/home/child.twig'

Note: the same example works fine in codeigniter.
I sure there's a configuration problem, I use the default configuration which comes with the composer package.

Please let me know if you see something wrong.

How to access renderBlock method?

Hi, I'd like to use the following method from Twig's \vendor\twig\twig\lib\Twig\Template.php;

public function renderBlock($name, array $context, array $blocks = array())

The following doesn't work:

$view =  View::make('twigtemplate', $data);
return $view->renderBlock("block");

Thanks.

Can't include templates different then *twig

It's not possible to include templates other then *.twig.
I'm not sure if it can be fixed, but I've thought that it's good to report it :)

There's simple workaround for this problem:

{{ view_make('my.template') }}

Сonflict with other packages

I use package frozennode/administrator and catch exception
Undefined index

The problem is solved if the provider TwigBridge\TwigServiceProvider is placed before Frozennode\Administrator\AdministratorServiceProvider

Problem can be reproduced with other package when use View::composer before registred TwigBridge

I think it should be added to the documentation or generate an error when View is initialized before TwigBridge

Error on access to a Eloquent relation from a template

I have 2 models ( User, Group ) with relations :

  • Group => hasMany => User
  • User => belongsTo => Group
// Controller
public function getIndex()
{
     $user = User::first();
     return View::make('view')->with('user', $user);
}

In a PHP view I wrote :

<?php echo $user->group->name; ?>

And it works fine but if I use a Twig view with :

{{ user.group.name }}

I get an error :

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 'name' in /vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php line 443") in "form.twig" at line 14.

If I get a property of the User class like {{ user.username }} it works ... seems that there's a problem with relations

Laravel helpers not working

I just created a new Laravel installation and only added TwigBridge but I'm experiencing some issues when using Laravel's own helpers.

For example:
{{ Form_open({url:'/test'}) }}
//
{{ Form_close() }}

Result:

//

This looks good, the only problem is that this is the result when I look via the browser, not the source code of the page.... When I add the |raw option at the end of each helper, then the form is displayed the correct way.

screen

All I changed in the config was the file extenion (from twig to tpl) and set the debug to true..
I have used this before, so I don't understand why it doesn't work anymore.

Function arguments are stripped from slashes

Not sure if this is an issue with TwigBridge or Twig (or my config), but when I try to use namespaces in my function (ie. custom functions or the aliases), the backslashes get stripped.
{{ url_action('Barry\MyController') }} // Action BarryMyController not found
{{ url_action('Barry\\MyController') }} //Works

Is this expected behavior, or is there something that I can do to fix this? Not a very big deal, but pretty annoying, as it works just fine in Laravel itself.

Not working... how best to debug?

Followed the readme exactly but no dice. Composer installed fine, Provider added, Twig syntax just not respected in any of my views. Ideas?

Loaders / Environment

Right now, the View and Environment classes are overridden. Is that really necessary?
You state that it is to get the original template name, but do you really need it? As stated in #59, you don't need it the first time, and the rest of the times, you can pass it directly to the loader.

You now transform the path from the Viewfinder to an array of paths and the relative name right? And then pass it to the Loader, to find the path again.
So why not use the original path in the first place? And for the paths to import in the views, why not just use the Viewfinder directly? This way you don't have to transform the path at all (except strip a possible .twig extension).
Then just use both (and possibly more loaders) in the ChainLoader.
See the examples here: https://github.com/barryvdh/laravel-twigbridge/tree/master/src/Barryvdh/TwigBridge/Loader

I installed TwigBridge, however it can't figure out view.engine.resolver

However, everytime I run the php artisan dump-autoload command, I get a {"error":{"type":"ReflectionException","message":"Class view.engine.resolver does not exist","file":"/www/sites/www.complete.com/vendor/laravel/framework/src/Illuminate/Container/Container.php","line":303}}

I am using Laravel 4.0.9

include(): Cannot redeclare class illuminate\config\loaderinterface

Hello... thanks for sharing this usefull package for Laravel 4...

Im having this issue after my last commit. I see this Whoops! page on my Laravel 4 site.

Symfony \ Component \ Debug \ Exception \ FatalErrorException
include(): Cannot redeclare class illuminate\config\loaderinterface
/var/www/web/username/htdocs/vendor/composer/ClassLoader.php

And when i commit some files and call git hook: [trigger:composer]
I see this error:

WARN: Composer threw 'RuntimeException'
WARN: PHP Fatal Error: Class 'TwigBridge\TwigServiceProvider' not found in
/var/www/username/htdocs/vendor/laravel/framework/src/Illuminate/Foundation/ProviderRepository on line 123
WARN: Fail

What i could do??

Thanks.

Composers and Creators

Your twigbridge (kind of) supports composing events, but it has some issues:

  • It checks for registered listeners, but this doesn't work for wildcards.
  • Only composing is called, not (the recently added) creating event.
  • If the check is removed, the composer is called twice?

Not really sure what the best behavior is, but it isn't really the same as Blade templates.

As far as I understand, Laravel calls the creator/composer for the master template already:
https://github.com/laravel/framework/blob/4.0/src/Illuminate/View/Environment.php#L119
and
https://github.com/laravel/framework/blob/4.0/src/Illuminate/View/View.php#L79

So you don't have to call it for the parent one, right? Only for the imported templates, which you do here: https://github.com/rcrowe/TwigBridge/blob/master/src/TwigBridge/Twig/Template.php#L25 in display().
So imho it should always run creator/composer, except for the master View.

In an example I wrote, I can easily check if it is the master template, or imported, but not sure what is the best for your case:
https://github.com/barryvdh/laravel-twigbridge/blob/master/src/Barryvdh/TwigBridge/TwigTemplate.php#L28

Unable to add Twig Extension through Event::listen()

Using this (like in the docs) :

Event::listen('twigbridge.twig', function($twig) {
    $twig->addExtension( new TwigBridge\Extensions\Example );
});

I give :

Error: Call to undefined method Illuminate\Events\Event::addExtension()

Because $twig is an instance of the Event class

View data not available

When I pass data to a view, the passed vars are not available in it.
I did follow the instructions exactly, and everything works fine, except this.

Here's the code:

return \View::make('igniscms::dashboard', ['test' => 'value']);

If I do a var dump, the data is in the Illuminate\View\View object, but it's not available on the view.

// This
var_dump(\View::make('igniscms::dashboard', ['user' => \Auth::user()]));exit;

// Dumps this
object(Illuminate\View\View)[184]
  protected 'environment' => 
    object(Illuminate\View\Environment)[84]
      protected 'engines' => 
        object(Illuminate\View\Engines\EngineResolver)[64]
          protected 'resolvers' => 
            array (size=3)
              ...
          protected 'resolved' => 
            array (size=1)
              ...
      protected 'finder' => 
        object(Illuminate\View\FileViewFinder)[82]
          protected 'files' => 
            object(Illuminate\Filesystem\Filesystem)[83]
              ...
          protected 'paths' => 
            array (size=1)
              ...
          protected 'hints' => 
            array (size=1)
              ...
          protected 'extensions' => 
            array (size=3)
              ...
      protected 'events' => 
        object(Illuminate\Events\Dispatcher)[74]
          protected 'container' => 
            object(Illuminate\Foundation\Application)[14]
              ...
          private 'listeners' (Symfony\Component\EventDispatcher\EventDispatcher) => 
            array (size=2)
              ...
          private 'sorted' (Symfony\Component\EventDispatcher\EventDispatcher) => 
            array (size=1)
              ...
      protected 'container' => 
        object(Illuminate\Foundation\Application)[14]
          protected 'booted' => boolean true
          protected 'serviceProviders' => 
            array (size=18)
              ...
          protected 'loadedProviders' => 
            array (size=18)
              ...
          protected 'deferredServices' => 
            array (size=32)
              ...
          protected 'bindings' => 
            array (size=35)
              ...
          protected 'instances' => 
            array (size=5)
              ...
          protected 'aliases' => 
            array (size=0)
              ...
      protected 'shared' => 
        array (size=3)
          '__env' => 
            &object(Illuminate\View\Environment)[84]
          'errors' => 
            object(Illuminate\Support\MessageBag)[85]
              ...
          'app' => 
            object(Illuminate\Foundation\Application)[14]
              ...
      protected 'extensions' => 
        array (size=3)
          'blade.php' => string 'blade' (length=5)
          'php' => string 'php' (length=3)
          'twig' => string 'twig' (length=4)
      protected 'composers' => 
        array (size=0)
          empty
      protected 'sections' => 
        array (size=0)
          empty
      protected 'sectionStack' => 
        array (size=0)
          empty
      protected 'renderCount' => int 0
  protected 'engine' => 
    object(TwigBridge\Engines\TwigEngine)[203]
      protected 'twig' => 
        object(Twig_Environment)[187]
          protected 'charset' => string 'utf-8' (length=5)
          protected 'loader' => 
            object(TwigBridge\Twig\Loader\Filesystem)[186]
              ...
          protected 'debug' => boolean false
          protected 'autoReload' => boolean true
          protected 'cache' => string '/server/studioignis/cms/app/storage/views/twig' (length=46)
          protected 'lexer' => 
            object(Twig_Lexer)[204]
              ...
          protected 'parser' => null
          protected 'compiler' => null
          protected 'baseTemplateClass' => string 'TwigBridge\Twig\Template' (length=24)
          protected 'extensions' => 
            array (size=5)
              ...
          protected 'parsers' => 
            object(Twig_TokenParserBroker)[205]
              ...
          protected 'visitors' => 
            array (size=2)
              ...
          protected 'filters' => 
            array (size=28)
              ...
          protected 'tests' => 
            array (size=10)
              ...
          protected 'functions' => 
            array (size=48)
              ...
          protected 'globals' => null
          protected 'runtimeInitialized' => boolean false
          protected 'extensionInitialized' => boolean true
          protected 'loadedTemplates' => null
          protected 'strictVariables' => boolean false
          protected 'unaryOperators' => 
            array (size=3)
              ...
          protected 'binaryOperators' => 
            array (size=24)
              ...
          protected 'templateClassPrefix' => string '__TwigTemplate_' (length=15)
          protected 'functionCallbacks' => 
            array (size=1)
              ...
          protected 'filterCallbacks' => 
            array (size=0)
              ...
          protected 'staging' => 
            object(Twig_Extension_Staging)[191]
              ...
      protected 'global_data' => 
        array (size=0)
          empty
  protected 'view' => string 'igniscms::dashboard' (length=19)
  protected 'data' => 
    array (size=2)
      'test' => string 'value' (length=5)
      'user' => 
        object(Flatline\Auth\MongolUser)[175]
          protected 'attributes' => 
            array (size=9)
              ...
  protected 'path' => string '/server/studioignis/cms/workbench/studioignis/igniscms/src/views/dashboard.twig' (length=79)

Problem with the AliasLoader extension ?

Hello,

There seems to be an issue with the usage of functions such as "html_style" in Twig templates, since I upgraded TwigBridge from 0.1.x to 0.3.x. It triggers the following error :

Twig_Error_Syntax
The function "html_style" does not exist in "layout.twig" at line 18

The line 18 in my template is as follows :

{{ html_style('css/normalize.css') }}

...and there's nothing else worth mentioning before or after this line.

From what I gathered, the AliasLoader extension is used to map calls to that kind of functions in Twig templates to the corresponding facade object and method. But I don't know exactly what's causing it to fail mapping HTML::style to html_style, like it used to in previous versions.

Note : I have tried clearing my Twig cache, my App cache, and I also recompiled (artisan optimize) my app, but none of these changed anything.

View Composer for extended template not running.

Hey I looked into your older tickets when you implemented the View::composer support and it looks like you went over this case, but for some reason I can't get it to run. If I change my composer to be based on the actual view called and not the extended template, my composer will run, so I am a little confused at what is wrong with my code or if this is still working.

In my "app/filters.php" file I added:

View::composer('layouts.basic', function($view){
  $menu = array(
    array(
      'uri' => '/app',
      'label' => 'Home',
      'isActive' => Request::is('app')
    )
  );

  $view->with('menu', $menu);
});

Then for my views I have it set up as such:

"app/views/layouts/basic.twig"

...
<div class="menu">{{ dump(menu) }}</div>
...

"app/views/pages/home.twig"

{% extends 'layouts.basic' %}
...

And in my "app/routes.php" I have it directing to a controller that basically does this for a view:

...
return \View::make('pages.home')->with($pageData);
...

Now if I change my composer to be based a target of "pages.home" instead, I will actually dump out my menu data. So I know the view composer is being hit, just not when I target an extended template.

Not sure if I am missing a configuration, but any help would be appreciated. I'll investigate into it further as well and report anything further I find.

Thanks
-Scott

Composing events fired twice

I had problems with my view composers, I'm using the master branch. When I dump the fired events with a small backtrace, it seems Illuminate/View/Environment fires one, and then later one, TwigBridge fires its own. The problem View passed in the event the core Environment class fires is missing the data bound on View::make while Twig's event has those.

I double checked, I don't have any composer twice somewhere and this happen for all the views. Any idea where it might come from ?

New tag needed for composer

When I try to install with the current L4 beta, I'm running into an issue with composer. It wants to use the twigbridge version tagged 1.1.12 but your update to composer.json (with the correct illuminate version) is after that. Any chance of a 1.1.13 tag?

(I'm a Mercurial user and git leaves me ... just weirded out -- that's why you're getting a bug report instead of a pull request.)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.