Here's the PHP code:
if ($var===0) {do something}
It "does something" only when $var is actually 0 (and if $var is not set, it doesn't work, so everything is OK).
However, Twig doesn't support === operator, and if I write:
{% if var==0 %}do something{% endif %}
it "does something" all the time (even when $var is not set). In order to fix it, I wrote such a code:
{% if var matches 0 %}do something{% endif %}
Is it a proper way to do === comparison in Twig, or I did something wrong here? If it's wrong, how should it be fixed?
You need to use same as in Twig for === comparisons:
{% set var1=0 %}
{% set var2='0' %}
{% if var1 is same as( 0 ) %}
var1 is 0.
{% else %}
var1 is not zero.
{% endif %}
{% if var2 is same as( 0 ) %}
var2 is 0.
{% else %}
var2 is not 0.
{% endif %}
{% if var2 is same as( '0' ) %}
var2 is '0'.
{% else %}
var2 is not '0'.
{% endif %}
Here is a twigfiddle showing it in operation:
https://twigfiddle.com/k09myb
Here is the documentation for same as also stating that it is equivalent to ===. Hope that helps you!
Twig doesn't have === but it has same as instead. See: https://twig.sensiolabs.org/doc/2.x/tests/sameas.html
So you could write:
{% if var is same as(0) %}do something{% endif %}
Eventually, you can use is defined to check whether the variable is set.
Related
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 %}
I'm trying to see if an array has a key. The first case returns 2 results 1-5 and , while the second seems to work fine.
Any ideea why is this happening ?
{% set options = {'1' : '1' , '1-5' : '5' , '1-12' : '12' } %}
{% set selected = '1-5' %}
Wrong check
{% for k,v in options %}
{% if k == selected %}
{{ k }}
{% endif %}
{% endfor %}
Right
{% for k,v in options %}
{% if k|format == selected|format %}
{{ k }}
{% endif %}
{% endfor %}
https://twigfiddle.com/c6m0h4
Twig will compile the "wrong check" in the following PHP snippet:
if (($context["k"] == (isset($context["selected"]) || array_key_exists("selected", $context) ? $context["selected"] : (function () { throw new RuntimeError('Variable "selected" does not exist.', 6, $this->source); })()))) {
Simplified this becomes
if ($context["k"] == $context["selected"])
Because the type of context["k"] (for the first iteration) is an integer, PHP will typecast the right hand part of the equation to an integer as well. So the equation actually becomes the following:
if ((int)1 == (int)'1-5')
and casting 1-5 to an integer becomes 1, making the final equation to:
1 == 1 which evaluates to true
You can test the fact that first key gets treated as integer with the following PHPsnippet by the way
<?php
$foo = [ '1' => 'bar', ];
$bar = '1-5';
foreach($foo as $key => $value) {
var_dump($key); ## output: (int) 1
var_dump($key == $bar); ## output: true
}
demo
I want to add key and value into array in twig file. But I am facing following issue "Twig_Error_Syntax: A hash key must be a quoted string or a number"
{% set phoneCount = 0 %}
{% set phoneNumbers = {} %}
{% for currPhone in currBroker.phones %}
{% if (currPhone.type == 'Work' or currPhone.type == 'Mobile') and phoneCount <= 2 and currPhone.number !='' %}
{% set phoneCount = phoneCount + 1 %}
{% set phoneNumbers = phoneNumbers|merge({ currPhone.type:currPhone.type }) %}
{% endif %}
{% endfor %}
{{ phoneNumbers|print_r }}
I just need the syntax of merging key and value into array.
I tried by giving static inputs and its works
{% set phoneNumbers = phoneNumbers|merge({ 'work':'(011)112-1233' }) %}
But its not working for dynmic input. Please help!!
You have to wrap your key in braces :
{% set phoneNumbers = phoneNumbers|merge({ (currPhone.type) : currPhone.type }) %}
Tested and working example :
{% set currPhone = {type: 'test'} %}
{% set phoneNumbers = {} %}
{% set phoneNumbers = phoneNumbers|merge({ (currPhone.type) : currPhone.type }) %}
{% dump(phoneNumbers) %}
I get :
array:1 [▼
"test" => "test"
]
I need to set some conditions in twig, so i have this:
{% if app.session.get('campaignVersion') is not null and is not '4.4d'}
...
{% elseif app.session.get('campaignVersion') is null or '4.4d' %}
...
{% endif %}
But i have errors with syntax and logic, maybe it must have an standard operator such as !=, what i'm doing wrong? Thx for help.
Twig is not a human language interpreter :-)
Twig is not able to implicitly know who is the subject in and is not '4.4d'.
Try with:
{% if app.session.get('campaignVersion') is not null and app.session.get('campaignVersion') != '4.4d' %}
Or for better readibility:
{% if app.session.get('campaignVersion') not in [null, '4.4d'] %}
A % is missing at the end of the first line
I have been stuck at this for a while now. I am new to twig and i am trying to iterate a code untill my variable becomes zero. I have tried this:
{% set total = 5%}
{% set i=1 %}
{% for total %}
{{i}}
{%set i=i+1%}
{% set total = total -1%}
{% endfor %}
and this
{% set i=1 %}
{% for total > 1%}
{{i}}
{%set i=i+1%}
{% set total = total - 1%}
{% endfor %}
but none are working.. What am i doing wrong?
Twig fors are more akin to PHP's foreachs (they are for iterating over a traversable). To achieve what you are describing you would do:
{% set nums = range(1, 5) %}
{% for num in nums|reverse %}
{{ num }}
{% endfor %}
In practice, you could set nums from your controller logic. Also note from the Twig manual:
Unlike in PHP, it's not possible to break or continue in a loop.
You can, however, skip elements with if. Manual example:
{% for user in users if user.active %}