Reputation:
I've got an string loaded from my DB, and global variable from my config.yml
. I want to check if variable is a part of array given below:
app.user.role ='["1","2","3","4","5","6","7","8","9","10","11"]'
I can't change that. It have to look like this.
I was checking it like this:
{% if VARIABLE in app.user.role %}
Global VARIABLE
is an integer (and I can't change that)
But when for example VARIABLE = 1
my statement returns true, because in app.user.role
we can find four 1
(in "1","10","11"
), but i want to find it just in "1"
not in "10","11"
.
What I want is to convert app.user.role
to array or find another way to check if variable is an element of my pseudo array.
I was trying to iterate through for
loop but app.user.role
but app.user.role
is not an array (actualy it is, but with one value ["1","2","3","4","5","6","7","8","9","10","11"]
).
Upvotes: 2
Views: 4661
Reputation: 36
The string looks like JSON. You can create a Twig Extension class and register there a function that simply returns in_array
:
<?php
class MyExtension extends Twig_Extension
{
public function getFunctions()
{
return [
new Twig_SimpleFunction(
'inarray',
[$this, 'inArray']
),
];
}
/**
* @param int $variable
* @param string $appUserRole
*
* @return bool
*/
public function inArray(int $variable, string $appUserRole): bool
{
return in_array($variable, json_decode($appUserRole));
}
}
Then in the template:
{% if inarray(VARIABLE, app.user.role) %}
Upvotes: 2
Reputation:
Found a solution. Not the best but it works.
{% set check = '"'~VARIABLE~'"' %}
{% if check in app.user.role %}
Now it's working...
Upvotes: 0