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 :-)