I'm trying to do an if statement with data passed to the twig file from the controller. Below is a line from the controller:
return $this->redirect($this->generateUrl('homepage', array('user' => $user, 'contact' => $contact)));
My goal is to do an if statement with the variable 'contact'. I checked the twig reference and it shows how to do an if statement but that would not work with 'contact'. Below is the code I tried, can somebody tell me what I'm doing wrong?
{% if {{ contact.id }} > 0 %}
{{ contact.addrLineOne }}
{% else %}
--
{% endif %}
You're almost there, just a small syntax modification will make your code working!
{% if contact.id > 0 %}
{{ contact.addrLineOne }}
{% else %}
--
{% endif %}
In Twig, curly braces means that you want to print the value of a variable or an expression. So you're statement in PHP would look like this :
if ((echo contact[id]) > 0)
echo contact[addrLineOne]; // or contact->addrLineOne() according to the context
else
--
Related
I have a twig template where I would like to test if an item begins with a certain value
{% if item.ContentTypeId == '0x0120' %}
<td><a href='?parentId={{ item.Id }}'>{{ item.BaseName }}</a><br /></td>
{% else %}
<td><a href='?{{ item.UrlPrefix }}'>{{ item.LinkFilename }}</a></td>
{% endif %}
The 0x0120 can look like that or be more complex like this 0x0120D52000D430D2B0D8DD6F4BBB16123680E4F78700654036413B65C740B168E780DA0FB4BX. The only thing I want to do is to ensure that it starts with the 0x0120.
The ideal solution would be to solve this by using regex but I'm not aware if Twig supports this?
Thanks
You can do that directly in Twig now:
{% if 'World' starts with 'F' %}
{% endif %}
"Ends with" is also supported:
{% if 'Hello' ends with 'n' %}
{% endif %}
Other handy keywords also exist:
Complex string comparisons:
{% if phone matches '{^[\\d\\.]+$}' %} {% endif %}
(Note: double backslashes are converted to one backslash by twig)
String contains:
{{ 'cd' in 'abcde' }}
{{ 1 in [1, 2, 3] }}
See more information here: http://twig.sensiolabs.org/doc/templates.html#comparisons
Yes, Twig supports regular expressions in comparisons: http://twig.sensiolabs.org/doc/templates.html#comparisons
In your case it would be:
{% if item.ContentTypeId matches '/^0x0120.*/' %}
...
{% else %}
...
{% endif %}
You can just use the slice filter. Simply do:
{% if item.ContentTypeId[:6] == '0x0120' %}
{% endif %}
You can always make your own filter that performs the necessary comparison.
As per the docs:
When called by Twig, the PHP callable receives the left side of the filter (before the pipe |) as the first argument and the extra arguments passed to the filter (within parentheses ()) as extra arguments.
So here is a modified example.
Creating a filter is as simple as associating a name with a PHP
callable:
// an anonymous function
$filter = new Twig_SimpleFilter('compareBeginning', function ($longString, $startsWith) {
/* do your work here */
});
Then, add the filter to your Twig environment:
$twig = new Twig_Environment($loader);
$twig->addFilter($filter);
And here is how to use it in a template:
{% if item.ContentTypeId | compareBeginning('0x0120') == true %}
{# not sure of the precedence of | and == above, may need parentheses #}
I'm not a PHP guy, so I don't know how PHP does regexes, but the anonymous function above is designed to return true if $longString begins with $startsWith. I'm sure you'll find that trivial to implement.
I'm working on a template and I need to check if something is an array. How do I do that in Twig?
I've tried
{% if my_var is iterable %}
{% for v in my_var %}
...
{% endfor %}
{% else %}
{{ my_var }}
{% endif %}
but it always prints my_var, even when my_var is really an array, as evidenced when it prints out
Array
Array
myusername
../data/table.sqlite3
Another way :
{% if my_var.count()>1 %}
If you don't want to create a custom filter use iterable, as per the docs :
iterable checks if a variable is an array or a traversable object
{% if myVar is iterable %} ... {% endif %}
Just add a custom filter:
$twig->addFilter('is_array', new \Twig_Filter_Function('is_array'));
Then use it like this:
{% if my_var|is_array %}
Here is the thing. A trainer can speak zero to many languages. I want to display the languages for one or several trainers on a page. Note that I'm working on a code I didn't start from scratch.
In my controller :
foreach ($trainers as $trainer){
$trainer_entity = $doctrine->getRepository('AppBundle:Trainer')->find($trainer["id"]);
$listLangues = $this->getDoctrine()
->getManager()
->getRepository('AppBundle:TrainerLangues')
->findByTrainer_id($trainer["id"]);
}
return [
'user' => $user,
'listLangues' => $listLangues,
'trainers' => $trainers,
];
In my twig file:
{% if listLangues %}
<b>Langues</b> :
{% for l in listLangues %}
{{ l.langue.name }}
{% endfor %}
{% endif %}
This works when the person is linked to languages, so listLangues not empty.
Otherwise I get
Notice: Undefined variable: listLangues 500 Internal Server Error -
ContextErrorException
I tried {% if listLangues is defined %} as well, but the system seems to block in the controller. It never happened to me before.
note that initializing $listLangues only leads to no display on the twig page.
Any idea?
what do you really want to display in your view?
Here is a simple tips, you could try in your controller:
/***/
public function yourAction()
{
return $this->render('your-template.html.twig', [
'user' => $this->getUser(),
'trainers' => $this->getDoctrine()->getRepository(Trainer::class)->findAll()
]);
}
/***/
Then, in your view (basic implementation)
{% for trainer in trainers %}
<h4>{{ trainer.name }}</h4>
{% if trainer.languages %}
<ul>
{% for language in trainer.languages %}
<li>{{ language.name }}</li>
{% endfor %}
</ul>
{% endif %}
{% endfor %}
Hope, it will help you.
If your array $trainers is empty, the foreach nevers loops so the $listLangues var is never defined.
Try declaring it as an empty array BEFORE the foreach :
$listLangues = array();
You need to instantiate $listLangues because if there isn't trainers the variable can't exist and code is broke.
Try to add this before your foreach:
$listLangues = null;
Or instantiate It with a value or what you want but declare It before your foreach to be sure that exists
Hi how use this part of code with twig,
$this->assign('title', 'Home');
not
echo $this->assign('title', 'Home');
I tried,
{% set assign = ('title', 'Home') %}
{% set this.assign = ('title', 'Home') %}
{% set assign = {'title', 'Home'} %}
{{ assign('title', 'Home') }}
But still don't work
Thanks you
I don't know about using $this in the context of a template (it would refer to some generated class instance), but you can perform arbitrary operations without printing by using the do statement.
The do tag works exactly like the regular variable expression ({{ ... }}) just that it doesn't print anything:
{% do 1 + 2 %}
To access the view itself when using TwigView, use the _view variable:
{% do _view.assign('title', 'Home') %}
I passed data in 3 languages to the twig template and display this data in this way:
{% set lang=app.request.get("lang")%}
{% for item in contests%}
{% if lang=="fa"%}
{{item.titlefa}}
{% elseif lang=="en"%}
{{item.titleen}}
{% elseif lang=="ar"%}
{{item.titlear}}
{% endif%}
{% endfor%}
It is wirking but I must create 3 if condition for each object in "contests"
How can i show data in this logic:
{% set lang=app.request.get("lang")%}
{{item.title~lang}}
{% endfor%}
that can call proper method in contest
You can use the attribute TWIG function for call at runtime a method name, as example:
{% set lang=app.request.get("lang")%}
{% methodname = 'title'~lang %}
{% for item in contests%}
{{ attribute(item, methodname) }}
{% endfor%}
Hope this help