3

When using Symfony2 and Twig together, if you need to do this:

<td>{{ myObject.method.parameter }}</td>

or just

<td>{{ myObject.parameter }}</td>

If what the twig file is trying to access is not set, an error will be thrown. Is there a cleaner way to prevent this other than writing this everywhere:

<td>{% if myObject.method.parameter is defined %}{{ myObject.method.parameter }}{% endif %}</td>

It has been nice working with Angular recently, because it doesn't seem to care.

timhc22
  • 7,213
  • 8
  • 48
  • 66

1 Answers1

4

A pure Twig solution would be to use the default filter:

http://twig.sensiolabs.org/doc/filters/default.html

It looks like this and works fine for me:

{{ myObject.it.is.not.designed|default('it is not defined') }}  

The default text can be an empty string ''.

Now you have to set the default for every variable. Unlike {% autoescape %}, it seems a filter cannot be defined for a larger code area. In order to make it simple, I would create a macro:

{% macro safeEcho(value) %}
  {{ value | default('') }}
{% endmacro %}

Don't forget to import:

{% import _self as helper %}

Test:

Test:{{ helper.safeEcho(echolabels.something.something_2) }}

If I would use this very often, I'd consider short names, although I do not use abbreviations usually: h.se()

More about macros:

http://twig.sensiolabs.org/doc/tags/macro.html

If you need this fundamentally, there might be possibilities to overwrite the Twig lexer:

http://twig.sensiolabs.org/doc/internals.html

I don't know Twig as a part of Symfony2 well. It might be that its configuration offers an other option:

http://symfony.com/doc/current/reference/configuration/twig.html

Finally, see here that this question was asked before with different answers.

How to check for null in Twig?

symfony, twig - default filter for all variables in template

Maybe the Twig developers should consider offering a "general variable default" option :-)

Community
  • 1
  • 1
peter_the_oak
  • 3,529
  • 3
  • 23
  • 37