En Twig, compruebe si existe una clave específica de una matriz
En PHP podemos comprobar si existe una clave en un array usando la función array_key_exists()
.
En el lenguaje de plantillas Twig podemos comprobar si existe una variable o la propiedad de un objeto simplemente usando una instrucción if
, como esta:
{% if app.user %}
do something here
{% else %}
do something else
{% endif %}
Pero, ¿cómo comprobamos si existe una clave de un array usando Twig? Lo intenté {% if array.key %}
, pero me da un error:
Key "key" for array with keys "0, 1, 2, 3...648" does not exist
Como una de las principales formas de pasar datos a una plantilla es usando arrays, parece que debería haber alguna manera de hacer esto. ¿Alguna idea?
53
3 answers
Ejemplo de ramita:
{% if array.key is defined %}
// do something
{% else %}
// do something else
{% endif %}
135
Author: phpisuber01,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-28 14:29:20
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-28 14:29:20
Puede usar la función ramita keys
{% if myVar in someOtherArray|keys %}
13
Author: Samir Patel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-23 21:23:06
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-23 21:23:06
Respuesta rápida (TL; DR)
- DeveloperTLindel quiere probar la existencia de clave de matriz en Twig.
- DeveloperTLindel quiere atrapar cualquier error asociado con undefined key.
- Esto se puede manejar usando el filtro
default
.
Respuesta detallada
Contexto
- Ramita 2.x (última versión a partir de Mié 2017-03-08)
- Uso general del
default
filtro.
Problema
- Escenario:
- DeveloperTLindel quiere probar la existencia de clave de matriz en Twig.
- DeveloperTLindel quiere evitar cualquier error o excepción causada por una clave potencialmente indefinida.
Solución
- DeveloperTLindel puede usar el filtro
default
. - El filtro
default
atrapa cualquier excepción debido a una variable indefinida, y permite la sustitución de cortocircuito de una alternativa valor. - El filtro
default
es encadenable.
Example01
{#- **************************************** 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__') -%}
Véase también
1
Author: dreftymac,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:10:32
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:10:32