Skip to content

Add support for a null-safe filter operator ?| #4788

Description

@ehymel

My twig templates are full of code where I have a parameter, usually a date, that I need to display if it exists:

{{ site.startDate ? site.startDate|date('m/d/Y') }}

It would be nice if this could be shortened to something like this:

{{ site.startDate ?| date('m/d/Y') }}

I know that I could just write a a custom date filter that handles null input, along the lines of below, but this seems a bit much:

#[AsTwigFilter(name: 'safe_date', needsEnvironment: true)]
    public function safeDate(Environment $env, $date, ?string $format = null, $timezone = null): string
    {
        if (empty($date)) {
            return '';
        }
        return $env->getExtension(CoreExtension::class)->formatDate($date, $format, $timezone);
    }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions