Getting current route twig - symfony

I want to get the current route on twig , I used this two code but It fail always
Code 1:
{% if app.request.get('_route') == 'my_route' %}
//Do something
{% endif %}
Code 2:
{% if app.request.attributes.get == 'my_route' %}
//Do something
{% endif %}

Use the "app_dev.php" at the end of your URL to debug and check what route is being used at the bottom. For example I show "route1" here:
Then in your twig template you can use something like this:
{% if app.request.attributes.get('_route') == 'route1' %}
<h1>test</h1>
{% endif %}
I verified this works. I'm using Symfony3 though.
Maybe also try instead of "app.request.attributes.get()", try these:
app.request.pathinfo
app.request.uri
See if those work.
Also if the route is indeed null, try:
{% if app.request.attributes.get('_route') == '' %}
<h1>test</h1>
{% endif %}

Related

Twig - loop default value

I am trying to print array from the cotroller into the twig temlate. I want to print "-" whenever array is NULL. My problem is that in for-loop case it writes nothing, however single row working fine. Is there some simple way how to do it correctly?
this is not working as i expected
{% for key in keywords|default('-') %}
{{ key~', '}}
{% endfor %}
this is working
{{ key |default('-')}}
You can use an {% else %} construct on a for loop to do something else if the array is null:
{% for key in keywords %}
{{ key~', '}}
{% else %}
-
{% endfor %}
See the documentation here.

How do you check if a form field has data in twig template that is rendering a controller

This is a follow up question to this one . What I want to know is how to check if the entity variable exist/is defined/not null. I thought I could do this:
{% if entity.orgId is defined %}
{{ render(controller(
'CompanyNameofBundle:OrgMember:test', {'orgid':entity.orgId})) }}
{% endif %}
But if entity.orgId is null I get an exception has been thrown during the rendering of a template ("The product does not exist").
Change your controller to return null instead of exception:
public function testAction($orgid = null) {
if (!$orgid) { return null; }
// Rest of code.
}
You have two options:
Don't call the render controller using the check
{% if entity.orgId is defined and entity.orgId is not null %}
Make the testAction in the OrgMemberController null-safe (check if the parameter orgid is null)
Try this:
{% if entity.orgId is defined %}
{% if entity.orgId is null %}
{# do something #}
{% else %}
{# do anythingelse #}
{% endif %}
{% endif %}

Twig: filter in an if condition

I want to use an filter in an if condition in Twig. The reason for this is a Symfony2 attribute, which I can't compare directly, I have to change it beforehand. I have started with this code:
{% if app.request.attributes.get('_controller')|split('::')|first == 'some\controller\name' %}
do something
{% endif %}
Unfortunately this does not function. So I thought I would use set before the comparison:
{% set controller = app.request.attributes.get('_controller')|split('::')|first %}
{% if controller == 'some\controller\name' %}
do something
{% endif %}
{{ controller }} {# would print 'some\controller\name' #}
Guess what? "do something" is not printed, even if the variable controller now exists and has the value I compare it with. What am I doing wrong?
Ok I tested it, Twig has a strange behavior. "\" is escaped or something like this.
I extended my twig environement with the var_dump function, check this:
{{ var_dump("Sybio\Bundle\WebsiteBundle\Controller\MainController") }}
//string(48) "SybioBundleWebsiteBundleControllerMainController"
{{ var_dump(app.request.attributes.get('_controller')|split('::')|first) }}
// string(52) "Sybio\Bundle\WebsiteBundle\Controller\MainController"
{{ var_dump("Sybio\\Bundle\\WebsiteBundle\\Controller\\MainController") }}
// string(52) "Sybio\Bundle\WebsiteBundle\Controller\MainController"
That's why your test is always false.
You need to double the backslashes of your compared string...
{% if app.request.attributes.get('_controller')|split('::')|first == 'some\\controller\\name' %}
do something
{% endif %}

Get ROLE of a user not logged in TWIG Symfony2

I would like to know how can i know if a user is granted when it's not the current user in twig.
I use this code for the current user:
{% if is_granted('ROLE_USER') %}
Delete
{% endif %}
But i would like to be able to do the same thing with ohter users that are not logged in at the moment.
Thank you.
Edit:
In fact i think there isn't a direct way with twig to test role of a user that is not authenticated.
So i did it directly in the twig template, test if a user is admin or not, then set var.
(in my question i was searching how to do in a list of users.)
{% set from_user_is_admin = false %}
{% for role in from_user.getRoles() %}
{% if role == 'ROLE_ADMIN' %}{% set from_user_admin = true %}{% endif %}
{% if role == 'ROLE_SUPER_ADMIN' %}{% set from_user_admin = true %}{% endif %}
{% endfor %}
{% if from_user_admin == false %}THIS USER IS NOT ADMIN{% endif %}
I think it would be much easier if you implemented an isGranted function in the User entity:
Class User implements UserInterface {
...
public function isGranted($role)
{
return in_array($role, $this->getRoles());
}
}
You can now easily check for granted roles in every layer of your application.
In PHP:
$user->isGranted("USER_ADMIN")
Or in Twig:
user.granted("USER_ADMIN")
If you need to check a role for the current user, you can do this in Twig:
app.user.granted("USER_ADMIN")
Note: the variable "app" is globally defined.
Note 2: this code may throw an exception if you use it outside the secured area of your app, since app.user would be NULL.
You can use similar statement to the above with "not" :
{% if not is_granted('ROLE_USER') %}
Delete
{% endif %}
or use else statement:
{% if is_granted('ROLE_USER') %}
Delete
{% else %}
{# something else for guest user, not logged in #}
{% endif %}
You should create either a twig macro, or a twig function.
Creating a macro is very simple, using your code:
{% macro admin_status(from_user) %}
{% set from_user_is_admin = false %}
{% for role in from_user.getRoles() %}
{% if role == 'ROLE_ADMIN' %}{% set from_user_admin = true %}{% endif %}
{% if role == 'ROLE_SUPER_ADMIN' %}{% set from_user_admin = true %}{% endif %}
{% endfor %}
{% if from_user_admin == false %}THIS USER IS NOT ADMIN{% endif %}
{% endmacro %}
You can then use it in the same file as {% _self.admin_status(user) %}. You may also move it to a separate file, and use twig's import tag to gain access to it.
Creating a twig function is a better option, for details see extending twig. It boils down to creating a regular function, that may be called from twig, so code like this becomes possible:
{% if user_is_admin(user) %}
You'll also need to read enabling custom twig extensions.
i did it this way, have this snippet in the global twig file, in my case layout.html.twig
{% set is_admin = false %}
{% if app.security.token.user.roles is iterable %}
{% for role in app.security.token.user.roles %}
{% if role == 'ROLE_ADMIN' or role == 'ROLE_SUPER_ADMIN' %}
{% set is_admin = true %}
{% endif %}
{% endfor %}
{% endif %}
then i can use anywhere
{% if is_admin %}....{% endif %}

Twig: How to get the first character in a string

I am implementing an alphabetical search.
We display a table of Names. I want to highlight only those alphabets, which have names that begin with the corresponding alphabet.
I am stumped with a simple problem.
How to read the first character in the string user.name within twig.
I have tried several strategies, including the [0] operation but it throws an exception.
Here is the code
{% for i in ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0-9'] %}
{% set has_user_starting_with_alphabet = false %}
{% for user in pagination %}
{% if user.name[0]|lower == i %}
{% set has_user_starting_with_alphabet = true %}
{% endif %}
{% endfor %}
{% if has_user_starting_with_alphabet %}
<li><span>{{ i }}</span></li>
{% endif %}
{% endfor %}
Is there some function like "starts_with" in twig?
Since twig 1.12.2 you can use first:
{% if user.name|first|lower == i %}
For older version you can use slice:
{% if user.name|slice(0, 1)|lower == i %}
Note: You may also use this notation:
{% if user.name[:1]|lower == i %}

Resources