简体   繁体   中英

how to set twig global default variable

Is there any way to set GLOBAL DEFAULT variable instead of setting for each one ?

{{ app.model.foo | default('not set') }}
{{ app.model.bar | default('not set') }}

The built-in default filter cannot do what you wish to achieve. Here's its complete code:

function _twig_default_filter($value, $default = '')
{
    if (twig_test_empty($value)) {
        return $default;
    }

    return $value;
}

But twig is easy to extend ! You can create your own twig extension, which registers a new filter, the code of it would look something like this:

function my_default_filter($value, $default = '')
{
    if (twig_test_empty($value)) {
        return $default ?: $this->default;
    }

    return $value;
}

Where your class has a $default property which you can set from your code, however you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM