less.js icon indicating copy to clipboard operation
less.js copied to clipboard

Scope Issue with nested each()

Open dwhiting10 opened this issue 7 years ago • 3 comments

I searched through other issues and didn't find anything that seemed relevant, but if this is a dupe I apologize in advance.

I am running into a storage scoping issue when trying to nest a couple each() loops:

Given

@size: small, large;
@elements: html, div, p;

each(@size, {

    @sizeval: @{value};

    each(@elements, {
        @{value} {
          &.@{sizeval}{
              foo: bar;
            }
        }
    });
});

Expected

html.small {
  foo: bar;
}
div.small {
  foo: bar;
}
p.small {
  foo: bar;
}
html.large {
  foo: bar;
}
div.large {
  foo: bar;
}
p.large {
  foo: bar;
}

Actual

html.html {
  foo: bar;
}
div.div {
  foo: bar;
}
p.p {
  foo: bar;
}
html.html {
  foo: bar;
}
div.div {
  foo: bar;
}
p.p {
  foo: bar;
}

It seems like the value of @sizeval is being re-assigned from the @{value} in the first loop (which is the value I want and would expect it to have) to @{value} in the second loop when @sizeval is evaluated in the second loop. Is this the expected behavior? Is there a way to assign @sizeval to the actual value of @{value} instead of the @{value} variable?

dwhiting10 avatar Jul 24 '19 15:07 dwhiting10

@dwhiting10 Yes, this is expected behavior and is the result of two Less features: Lazy evaluation of variables (the variable is not evaluated until it needs to produce a static value), and scope-level values (each variable has a value and only one value no matter where it's evaluated within that scope).

If you're coming from an imperative language (like Sass), instead of a declarative styling language like CSS or Less (which builds on CSS's declarative principles), these might not be intuitive.

What you can do is pass in an anonymous mixin signature to use a different variable name in the inner each() block, like this:

@size: small, large;
@elements: html, div, p;

each(@size, {

    @sizeval: @{value};

    each(@elements, #(@val) {
        @{val} {
          &.@{sizeval}{
              foo: bar;
            }
        }
    });
});

Hope that helps!

matthew-dean avatar Jul 24 '19 19:07 matthew-dean

Closing as expected behavior.

matthew-dean avatar Jul 24 '19 19:07 matthew-dean

Ok, thanks for clarifying that @matthew-dean

dwhiting10 avatar Jul 25 '19 01:07 dwhiting10