Reputation: 2265
In PHP we can check if a key exists in an array by using the function array_key_exists()
.
In the Twig templating language we can check if an variable or an object's property exists simply by using an if
statement, like this:
{% if app.user %}
do something here
{% else %}
do something else
{% endif %}
But how do we check if a key of an array exists using Twig? I tried {% if array.key %}
, but it gives me an error:
Key "key" for array with keys "0, 1, 2, 3...648" does not exist
As one of the primary ways of passing data into a template is using arrays, it seems like there should be some way of doing this. Any thoughts?
Upvotes: 110
Views: 162740
Reputation: 330
SYMFONY 6
solution is quite simple TWIG is looking for variable passed when $this->render
is called in Controller.
create your pack data like
$options = [
'companyLogo' => $company->getCompanyLogoLink(),
'companyName' => $company->getCompanyShortname(),
'menuItem' => $companyMenuCategories,
];
pass it to TWIG
return $this->render('folder/template.html.twig', [ 'o' => $options, ]);
in twig just look for 'passed' key ( o ) and array data with it
{% if o.companyName is defined %}
{{ o.companyName }}
{% endif %}
Upvotes: 2
Reputation: 32360
default
filter.default
filter.default
filter.default
filter catches any exceptions owing to undefined variable, and allows short-circuit substition of an alternate value.default
filter is chainable.{#- **************************************** testing for a single key in associative array -#} {%- set mystring = myarray['key-no-existo'] |default('__BLANK__') -%} {#- **************************************** testing for a multiple keys in associative array -#} {%- set mystring = myarray['alpha'] |default(myarray['bravo']) |default(myarray['charlie']) |default('__BLANK__') -%}
Upvotes: 4
Reputation: 895
You can use the keys
twig function
{% if myVar in someOtherArray|keys %}
Upvotes: 47
Reputation: 7715
Twig example:
{% if array.key is defined %}
// do something
{% else %}
// do something else
{% endif %}
Upvotes: 250