I think the issue with trying to set a variable in a macro is that the variable is limited to the scope of the macro you are triggering, so {% set parent = thisEntry %}
is available within the scope of your macro, but doesn't define it for the rest of your template.
Macros are comparable with functions in regular programming languages. They are useful to put often used HTML idioms into reusable elements to not repeat yourself.
Macros differs from native PHP functions in a few ways:
- Default argument values are defined by using the default filter in the macro body;
- Arguments of a macro are always optional.
- But as with PHP functions, macros don't have access to the current template variables.
Taken from the Twig docs
So due to the limitations in scope and the nature of macros, they are meant to be used to just output reusable code, not set and define logic in your templates. So everything is just rendered as a string (models have their __toString()
method called)
The way you could get this to work for you is to just output whether or not the logic in your macro is true or null, then do the rest of the logic in your template, something like:
{% macro hasParentEntry(thisEntry) %}
{% import _self as self %}
{% if thisEntry.parent|length %}
{# would output 1 #}
{{ true }}
{% else %}
{# or just output null #}
{{ null }}
{% endif %}
{% endmacro %}
Then in your template do something like:
{# This will either be true or null #}
{% set parent = self.hasParentEntry( entry ) %}
{% if parent %}
{# this will set your parent variable to the entry model or leave the variable as null #}
{% set parent = entry.parent %}
{% endif %}