rcrowe / TwigBridge

Give the power of Twig to Laravel
MIT License
894 stars 167 forks source link

Custom Tag #343

Closed christophemassin closed 6 years ago

christophemassin commented 6 years ago

Hello,

I m currently trying to add custom tag to one project. My goal is to reach something more look like : https://github.com/spatie/laravel-permission/blob/c3c98a97e037950fe7a5dd1f1362626a4d95ea37/src/PermissionServiceProvider.php

So in my twig view , i ve add :

{% hasrole admin %}
    <a href="url"> Link </a>
{% endhasrole %}

I ve create a new class

class Role extends Twig_Extension
{
    public function getTokenParsers()
    {
        return array(
            new HasRoleParser(),new EndHasRoleParser()
        );
    }
}

And created the two sub class :

class HasRoleParser extends \Twig_TokenParser
{
    public function parse(Twig_Token $token)
    {
        $parser = $this->parser;
        $stream = $parser->getStream();

        $role = $stream->expect(Twig_Token::NAME_TYPE)->getValue();
        $guard = null;

        return "<?php if(auth({$guard})->check() && auth({$guard})->user()->hasRole({$role})): ?>";
    }

    public function getTag()
    {
        return 'hasrole';
    }

}

and

class EndHasRoleParser extends \Twig_TokenParser
{
    public function parse(Twig_Token $token)
    {
        return '<?php endif; ?>';
    }

    public function getTag()
    {
        return 'endhasrole';
    }

}

and in my twigbridge file, i set it up like this


        'enabled' => [
            \TwigBridge\Extension\Loader\Facades::class,
            \TwigBridge\Extension\Loader\Filters::class,
            \TwigBridge\Extension\Loader\Functions::class,

            \TwigBridge\Extension\Laravel\Auth::class,
            \TwigBridge\Extension\Laravel\Config::class,
            \TwigBridge\Extension\Laravel\Dump::class,
            \TwigBridge\Extension\Laravel\Input::class,
            \TwigBridge\Extension\Laravel\Session::class,
            \TwigBridge\Extension\Laravel\Str::class,
            \TwigBridge\Extension\Laravel\Translator::class,
            \TwigBridge\Extension\Laravel\Url::class,
            \TwigBridge\Extension\Laravel\Gate::class,
            \TwigBridge\Extension\Laravel\Html::class,
            \TwigBridge\Extension\Laravel\Form::class,

            \Project\Libs\Twig\Role::class,
        ],

However, i end up with this answer "Lexer or parser ended up in unsupported state".

Should i define the tag in another extensions , is there a thing i missed in the twigbridge for configuring new tags, or do you see any errors in the code ?

Thanks a lot !

christophemassin commented 6 years ago

Should i return a twig node instead of string in my parse class ?

bilogic commented 5 years ago

@christophemassin how did you finally solve the error? thank you.