I know it is easy to check if a variable is defined using
{# defined works with variable names #}
{% if foo is defined %}
...
{% endif %}
and to set a variable if it is undefined using:
{% set foo = 'bar' %}
Is there a way to set the variable as undefined? I have a variable that is passed to an twig html file and it is not always passed, and I just came across a situation where it could be null. When it is null, I would like to set it to undefined because the logical statements through the rest of the file work correctly and it's a pain testing for defined first, then null a second time each time I use this variable.
I came across this conversation and wanted to know if anyone else has a solution to either unset the variable, or a better way to set for a variable that can be undefined or null.
Updated with code: I'm working on my backend Admin section. For various reason I did not use the SonataAdmin and wanted to build my own. In this area I can view a summary all users and in some pages I can view and edit parts of a user's profile. I have a header twig file that contains links to the summary pages, then another row that contains links to the user's profile sections.
For my route admin_profile_show - I need to include the user to load the correct page, but if the user is null here, this will cause an error because it cannot reach the username property.
{% if user is defined %}
{{ path('admin_profile_show', { 'username': user.username}) }}
...other routes and links
{% endif %}
I guess my real problem is that I allowed a case where the username can be null so it is defined, but null. Before I change the logic of other files, I wanted to know if there is an unset variable that would work as follows:
{% if user is null %}
{% unset user %}
{% endif %}
null? If you have strict variables set to false (this is the default), trying to print or doing anything with the variable does not throw any errors. Can you show some code?{% if user is defined and user.username is defined and user.username is not null %}?{% if user|default %}...{% endif %}