How to reproduce:

Tried to add something to the outermost <ul> in menu.html.twig, but the line:

{% if menu_level == 0 %}
    {% if menu_level == 0 %}
      <ul{{ attributes.addClass('my-cool-class') }}>
    {% else %}
      <ul class="menu">
    {% endif %}

my-cool-class does not show up in markup, instead I only see <ul class="menu">.

It appears that when we pass 0 to the macro this if statement comes back as false.


wesruv created an issue. See original summary.

wesruv’s picture

If you change the first invocation of the macro to pass '0' (a string, instead of a number) and check for '0', that if statement will come back true.

We don't want to do that though, so I also tried:

    {% if menu_level|number_format == 0 %}

|number_format by default will strip off all decimal places. This worked, but seems odd that I have to do this.

Unsure of the best way to fix this, is appending |number_format acceptable for core?

Would it be better if we fixed something in twig so that 0 was an integer and didn't become a float (I'm assuming that's what's happening)?

cilefen’s picture

Perhaps try sameas for a strict comparison.

joelpittet’s picture

Do you know where it's made a string?

wesruv’s picture

Blurg! This was my bad, I was convinced that the issue was that if statement.

The thing that got me debugging was a var I declared with {% set ... %} outside of the {% macro ... %} in menu.html.twig. It looks like the variables declared outside of in the same file macro don't make it inside.

In my debugging I was convinced 0 was getting turned into a float and == wasn't evaluating correctly.

Seems a bit odd that variables don't make it inside of macro's, but I suppose there's a reason. Not sure there's anything to do to alleviate confusion. Maybe Sensio Lab's docs page could mention how scope works in macro's, but that's nothing for us to do differently.


wesruv’s picture

Status: Active » Closed (works as designed)
wesruv’s picture

Made documentation ticket in Sensio Labs docs since I could find anything documenting how scope works with macros.