Reputation: 2436
I’m currently facing a very strange problem in a Twig template (Symfony v2.8.9; Twig v1.24.1). The basic outline is: I’m trying to overwrite a block in a child template when a specific condition is met.
Here’s a snippet of my template:
{% extends "@App/search/resultList.html.twig" %}
{% if category.teaser %}
{% block description %}{{category.teaser.doSomething()}}{% endblock %}
{% endif %}
This code leads to the following error:
Impossible to invoke a method ("doSomething") on a null variable in @App/search/categoryResult.html.twig
The teaser property of the category indeed is null, which is okay and what the check is for.
I also tried an explicit {% if category.teaser is not null %}
which also didn’t work and resulted in the same error.
Now for the really weird part (or maybe I’m just not seeing it why this wouldn’t be weird):
If I change the code to
{% block description %}
{% if category.teaser %}
{{category.teaser.doSomething()}}
{% endif %}
{% endblock %}
it works as intended (mostly, at least, because the parent block will always be overwritten).
This error seems to happen only in the Symfony dev environment.
It seems:
# Twig Configuration
twig:
debug: true
strict_variables: true
has something to do with it, which explains the dev environment only. If both values are set to false
it works correctly.
Has anybody ever encountered a problem like this and solved it? Any help in solving this issue would be much appreciated.
Upvotes: 1
Views: 805
Reputation: 291
You have done the best practice by testing whether the variable is null or not.
In many other languages you can’t do something on a null. You can use the dump()
function to check your variables.
Upvotes: -2
Reputation: 46
As far as I know, it is not possible to conditionally override a block in twig, see also How can I conditionally override a TWIG layout block?
Upvotes: 3