0
votes

This works in blade, but how can I do this in twig? Twig throws the following error: "An opened parenthesis is not properly closed. Unexpected token "punctuation" of value ":" ("punctuation" expected with value ")")"

<li {{ (Request::is('admin/users') ? 'class=active' : '') }}>
    <a href="{{ route('users') }}">
        Users
    </a>
</li>
5
Twig is explicitly set up to prevent raw PHP, IIRC. - ceejayoz
You have to extend twig to chain the method you want to call in twig - DarkBee

5 Answers

2
votes

I found the answer myself. I am using Laravel 5.1, with rcrowe/TwigBridge. I am able to do this:

{{ app.request.is('admin/users') ? 'class=active' }}
0
votes

You can access the request data within twig. This example works with Twig in Symfony3.

{% if app.request.requestUri == "admin/users" %} class='active'{% endif %}

or as a ternary operator

{{ app.request.requestUri == "admin/users" ? 'class="active"' }}
0
votes

The if statement in Twig is comparable with the if statements of PHP.

In the simplest form you can use it for multiple branches elseif and else can be used like in PHP. You can use more complex expressions there too:

{% if kenny.sick %}
    Kenny is sick.
{% elseif kenny.dead %}
    You killed Kenny! You bastard!!!
{% else %}
    Kenny looks okay --- so far
{% endif %}

as mentioned in :

https://twig.sensiolabs.org/doc/2.x/tags/if.html

However your example is ok you only need to get rid of the extra parenthesis ex:

<li {{ Request::is('admin/users') ? 'class=active' : '' }}>
<a href="{{ route('users') }}">
    Users
</a>

0
votes

it wasn't a problem with the extra brackets. Here is a TwigFiddle to show you:

https://twigfiddle.com/623sqv

The ternary is much easier than using an if statement, and your code is simplified significantly. You can read about it in my article on JSON and Twig Ternary Operator, and also Using null-coalescing operator.

You just need to always figure out how to do the comparison in the ternary properly. Hope this helps!

0
votes

Twig bridge provide an extension to the Request facade of laravel. It also provide the other extensions. Check here : https://github.com/rcrowe/TwigBridge#extensions

Instead of :: you need to use it with _ like this:

{{ request_is('admin/users') ? 'class=active' }}