Bogdan  Dubyk
Bogdan Dubyk

Reputation: 5564

Twig use constant as attribute

I want to pass constant as an attribute in the twig template.

Code looks like this: {% if presenter.hasErrors(constant('Admin\App\ViewPresenters\EditorPresenter::FORM_ERRORS') )%} and it throwing error Message: Argument 1 passed to Admin\App\ViewPresenters::hasErrors() must be of the type string, null given, called in /vendor/twig/twig/src/Extension/CoreExtension.php on line 1527, as far as I understand twig did not recognize it's an constant. Is there any wat to pass constant in twig as an argument?

Upvotes: 0

Views: 101

Answers (1)

DarkBee
DarkBee

Reputation: 15583

In twig a backslash is used to escape special characters e.g. {{ '\'' }} will output '. So to create a litteral backslash in twig you need to "escape" the backslash

{{ constant('Admin\\App\\ViewPresenters\\EditPresenter::FORM_ERRORS') }}

You can see the difference in the outputted source code twigfiddle:

{{ constant('Admin\App\ViewPresenters\EditPresenter::FORM_ERRORS') }}

PHP source

echo twig_escape_filter($this->env, twig_constant("AdminAppViewPresentersEditorPresenter::FORM_ERRORS"), "html", null, true);
{{ constant('Admin\\App\\ViewPresenters\\EditorPresenter::FORM_ERRORS') }}

PHP source

echo twig_escape_filter($this->env, twig_constant("Admin\\App\\ViewPresenters\\EditorPresenter::FORM_ERRORS"), "html", null, true);

demo

Upvotes: 2

Related Questions