Inject constant param form getter in twig

100 Views Asked by At

I have defined constant in my entity like:

$fieldName = User::METADATA_OF_USER

It's passed as the entity getter param:

public function getMetaDataField($fieldName)
{
    $metadata = json_decode($this->metadata, true);

    return $metadata[$fieldName] ?? null;
}

When I try to pass it in twig:

{ item.metadataField }}

it requires that fieldName param as constant.

I tried some solution of twig constants but non of them worked for me. I there any way to inject that constant in the view?

1

There are 1 best solutions below

0
On

According to Twig documentation, you need to use the constant function :

{{ item.getMetaDataField(constant('Namespace\\User::METADATA_OF_USER')) }}
// or
{{ item.getMetaDataField(constant('METADATA_OF_USER', instance)) }}

Note the \\.