George
George

Reputation: 1499

How to set variable as undefined?

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 %}

Upvotes: 2

Views: 8944

Answers (1)

xurshid29
xurshid29

Reputation: 4210

As F21 mentioned above, it's not a good practice modyifing data in template, but if you really want to to this, you can simply extend Twig to do this work (I mean you can create you own functons by extending it), Here is a simple example:

class STWebExtension extends \Twig_Extension
{

    /**
     * @return array|\Twig_SimpleFunction
     */
    public function getFunctions()
    {
        return [
            new \Twig_SimpleFunction('array_keys', [$this, 'array_keys']),
        ];
    }

    /**
     * @param array $input
     * @param null $search_value
     * @param null $strict
     * @return array
     */
    public function array_keys(array $input, $search_value = null, $strict = null)
    {
        return array_keys($input, $search_value, $strict); //here we are simply returning PHP's built-in array_keys function.
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'st_web_extension';
    }
}

Upvotes: 0

Related Questions