Skip to content

Interpolation of variable, mixin and function names (a.k.a. "Dynamic" variables/mixins/functions) #2702

Closed

Description

@WalkerCodeRanger

Using less 2.5.1 on http://less2css.org I can use variable variable Names to access a variable.

@var-name: "foo";
@foo: 45px;
.selector
{
    width: @@var-name;
}

Outputs:

.selector {
  width: 45px;
}

However when I try to declare the varible the same way, it gives an error:

@var-name: "foo";
@@var-name: 45px;

.selector
{
    width: @@var-name;
}

Gives:

ParseError: Unrecognised input on line 2, column 1:

1 @var-name: "foo";
2 @@var-name: 45px;
3 

The real world use case for this is I would like to have a grid framework that supports a variable number of breakpoints the user can change the names of. So I need to take a list of screen size names and declare a bunch of variables based on those. i.e.

@screen-size-names: xs, s, m, l, xl;
@screen-breakpoints: 544px, 7568px, 991px, 1200px;

And then use mixins to declare variables like @screen-s-min, @screen-m-max etc.

Activity

  1. rjgotten commented on Sep 24, 2015

    @rjgotten
    Contributor

    So I need to take a list of screen size names and declare a bunch of variables based on those.

    No. You need to declare keyed dictionaries; which you can build with lists...

  2. WalkerCodeRanger commented on Sep 24, 2015

    @WalkerCodeRanger
    Author

    @rjgotten I don't know what you mean when you say "keyed dictionaries; which you can build with lists". Can you provide a reference to an example or an example less?

  3. seven-phases-max commented on Sep 24, 2015

    @seven-phases-max
    Member

    Can you provide a reference to an example or an example less?

    This depends on the code you need to use such "variables" in. In general yes, the need for such variable-variable-names hints that there's something wrong with the approach (just think of it: you define something with unknown name to represent a value you would refer to later by the same unknown name... It does not make any sense really). And yes, lists/arrays and more "structured" (whatever this could mean in general) programming are much more clean and straight-forward (compared to both hypothetical variable-name-variable-definition and variable-name-variable-access (which is just yet another closely related anti-pattern of "moving every thing into a dedicated global variable")).

    A simplest example (just example, guessing you would use those variables for some grid generation) would be:

    @devices:
        s   544px,
        m   768px,
        l   991px,
        xl 1200px,
        z  2400px;
    
    .make-grid-colomns();
    .make-grid-colomns(@i: length(@devices)) when (@i > 0) {
        .make-grid-colomns(@i - 1);
        @device: extract(@devices, @i);
        @name:   extract(@device, 1);
        @size:   extract(@device, 2);
        @media (min-width: @size) {
            column-@{name}-bla-bla {
                blee-blu: blo-bla;  
            }
        }
    }

    But there're too many variations/patterns and zillion of other tips and tricks to use in particular situations (for a concrete use-case it's better to ask at SO or so).

  4. WalkerCodeRanger commented on Sep 24, 2015

    @WalkerCodeRanger
    Author

    @seven-phases-max Thanks, I now understand what he meant by "keyed dictionaries" I didn't realize you could do that, though I guess it makes sense given that lists can be separated with commas or spaces.

    I still think I need the functionality I filed this ticket for. Normally, I would agree that defining "something with unknown name to represent a value you would refer to later by the same unknown name... It does not make any sense really." If this were simply my own style sheet I would agree with you. However, I am trying to write a library something like bootstrap. The ability to define variable variables means that users of my library could change the number and names of the breakpoints and then have access to variables with those names. That will be much more straightforward for a user of my library than understanding how to pull things out of lists etc. So a hypothetical user of my library might do something like:

    @devices:
        tiny   340px,
        small  768px,
        big   1200px;
    
    @media @screen-tiny-only
    {
        .some-class
        {
            color: #123;
        }
    }
    

    From their perspective, there are no unknown names. They know that the names should be tiny, small, and big. They directly use a variable with a reasonable name to them.

  5. seven-phases-max commented on Sep 24, 2015

    @seven-phases-max
    Member
    @devices:
        tiny   340px,
        small  768px,
        big   1200px;
    
    @media @screen-tiny-only ...

    The main problem of this code is that if you add another screen size ("very-big") to the arrays above it will have no effect until you also explicitly write @media @screen-very-big-only for every case you need it, so it spoils the very idea of "dynamic" names (i.e. if you have to know it must be @screen-very-big-only then it's no point in having those values as a list(s)).

    (And for a more complex use-case, one can always get use of something like @screen-very-big-only: ... at(@devices, very-big) ... or so).

  6. WalkerCodeRanger commented on Sep 24, 2015

    @WalkerCodeRanger
    Author

    That isn't a problem because I am not expecting people to add device sizes to an existing project. Rather I am assuming they will be defined project to project near the beginning of that project.

  7. seven-phases-max commented on Sep 25, 2015

    @seven-phases-max
    Member

    That isn't a problem because I am not expecting people to add device sizes to an existing project.

    Then there's no need for lists (that's the main point - if you use dedicated vars you don't need any lists, if you use a list of these values you don't need vars).

    In other words, if you expect @screen-tiny-only to explicitly appear in either media query, there's no way a dynamic var definition (hidden and cluttered in mixins and/or some scary interpolations) can be better than the self-documented explicit @screen-tiny-only: value; definition.

  8. WalkerCodeRanger commented on Sep 25, 2015

    @WalkerCodeRanger
    Author

    I don't think you are understanding what I am doing. Let's imagine that Alice and Bob both download my library.

    My Library

    @devices:
        s   544px,
        m   768px,
        l   991px,
        xl 1200px;
    
    // Mixins that dynamically declare @screen-s-min, @screen-m-max for each device.
    

    Alice's Project

    @import "library.less"
    
    @media @screen-xl-only
    {
        // ...
    }
    

    Bob's Project

    @import "library.less"
    
    @devices:
        tiny   340px,
        small  768px,
        big   1200px;
    
    @media @screen-tiny-only
    {
        // ...
    }
    

    Bob is able to change the device list for his project, then use natural variables. So I do need to declare variable variables. My library needs to be dynamic and then various users of it need to use explicit variables like @screen-xl-only and @screen-tiny-only.

  9. seven-phases-max commented on Sep 25, 2015

    @seven-phases-max
    Member

    I don't think you are understanding what I am doing.

    Well, no, actually I do understand it perfectly. As I mentioned above if you want a fully customizable set of media queries forget about dedicated global vars. Bob's project may look like:

    @import "library.less";
    
    @devices:
        tiny   340px,
        small  768px,
        big   1200px;
    
    .media(tiny, {
        // ...
    });

    (just one of possible syntaxes).

    What I can't actually understand in your example is that how the code in your library would know what identifiers Bob used for his devices? Does the library have any media dependent CSS at all? Or this conversion from a list to global vars is the only purpose of the library? And if it's not, could you also elaborate what else (media related) code/stuff the library has?

  10. matthew-dean commented on Sep 25, 2015

    @matthew-dean
    Member

    I have to concur with @seven-phases-max and @rjgotten. "Defining" variable variables doesn't make sense, because it is, by nature, a referential syntax. And they're suggesting other patterns to achieve the same thing, and I could think of a few more to solve the same problem.

    For example, if Bob or Alice need to override the value of a global var, it would be as simple as:

    @screen-xl-only: 849px;
    

    If, however, Bob wanted to change the NAME of that var, it would be as simple as:

    @screen-hugetastic-only: @screen-xl-only;
    

    ...and then he could use @screen-hugetastic-only to his heart's content. So I don't think you need lists or extract loops at all. I don't really use lists, because I find Less loops a kind of anti-pattern, but that's more my personal preference.

  11. WalkerCodeRanger commented on Oct 1, 2015

    @WalkerCodeRanger
    Author

    First, setting aside my use case for a moment, I think it is just a matter of consistency. If you document that @@something is a variable variable, then I would expect to be able to use it anyplace I would put a variable name. I can do that, except I can't put it on the left hand side of a declaration. That feels inconsistent to me.

    Second, since there are some questions about the library I am thinking of creating I will try to provide some more detail. The plan is that it would be a mixin only library. Initially, it would support responsive grids and media queries. Over time I would hope it would grow to incorporate lots of other functionality like Bootstrap except only as mixins so users weren't forced into one way of organizing styles and constantly surprised by the millions of styles the framework applies. I'm sure some of these additional mixins would be affected by the media queries. I think it would be great to add features along the lines of Compass as well though I am not that familiar with it. I like less more than Sass and think that the lack of a really great mixin library is part of what is pushing people to Sass. When creating a library, I think end user syntax and clarity is very important to adoption. It makes sense for the library authors to jump through hoops and experience pain to create a good experience for users. I am open to alternate syntaxes, but so far haven't seen one I think is as clear as what could be done if I could declare variable variables. I readily admit I am not a Less guru, so there may be a good one I am not aware of yet. With all that said, something more concrete will probably help to clarify.

    In the discussion below, I will describe the API of the library without going into all the mixins it would take to create that.

    My library should support not just re-definable breakpoints, but a variable number of breakpoints since different sites work well with a different number of breakpoints. When changing the number of breakpoints, it makes sense to rename them.

    @screen-size-names: xs, s, m, l, xl;
    @screen-breakpoints: 544px, 768px, 991px, 1200px;
    

    I am using two different lists because there is one more screen size name than there are breakpoints (breakpoints divide the screen sizes into ranges).

    Based on the screen size names (possibly overridden by a customer), there would be mixins allowing the creation of what bootstrap calls a container. This defines in much greater detail the behaviour of the page width. An example usage might be:

    @page-default-margin: 16px;
    
    .my-page
    {
        .page();
        .page-xs-fluid(@page-margin: 8px);
        .page-s-fluid();
        .page-m-fixed();
        .page-l-fixed();
        .page-xl-fixed();
    }
    

    This allows the user to control for each screen size whether the the page is fluid or fixed size and what the margins and padding should be. In general, there are two mixins per page size @size. They are .page-@{size}-fluid(@page-padding: @page-default-padding; @page-margin: @page-default-margin) and .page-@{size}-fixed(@page-padding: @page-default-padding; @page-margin: @page-default-margin).

    When laying out elements on the page, there are a set of mixins that work similar to bootstrap grids (except they use inline-block instead of float). Rows are created using:

    .grid-row(@gutter: @grid-default-gutter) { /* ... */
    .grid-row-align(@align) { /* ... */ }
    .grid-row-vertical-align(@align) { /* ... */ }
    

    Then, for each screen size @size there are mixins:

    .grid-cell-@{size}(@width; @gutter: @grid-default-gutter; @columns: @grid-default-columns) { /* ... */ }
    .grid-cell-@{size}-offset(@width: @gutter: @grid-default-gutter; @columns: @grid-default-columns) { /* ... */ }
    .grid-cell-@{size}-push(@width; @columns: @grid-default-columns) { /* ... */ }
    .grid-cell-@{size}-pull(@width; @columns: @grid-default-columns) { /* ... */ }
    

    This set of mixins allows users to have different numbers of columns and different gutter width for different elements.

    Up to this point everything I have described can be done with less today.

    Given that the user has used many mixins each named after the screen sizes that they have potentially customized, when they need to do some media query for a style they are applying, it seems natural to them that they should be able to use variables with the same names. i.e.

    @media @screen-tiny-only
    {
        .some-class
        {
            color: #123;
        }
    }
    

    There would be a set of such variables for each screen size @size. There would be @screen-@{size}-only, @screen-@{size} (that size and up), and @screen-@{size}-down. (I know that was not valid syntax but I thought it would be a clear way to express what I meant). There would be additional media query variables like @screen-high-res and other useful variables like @screen-@{size}-min and screen-@{size}-max (the min and max size for given screen size).

    This last functionality is what I would use declaring variable variables for. In this context, I think it makes a lot of sense and provides the most intuitive syntax to the user.

    If something I have said is unclear, I'm happy to answer questions. However, at this point I think I have pretty much stated my case for this feature. If you don't agree that is fine. I leave it up to whatever process the less community has for deciding what features make it into the language. However, to keep less relevant I would strongly encourage that features like this and other powerful features needed to create advanced mixin libraries be added. I don't expect typical users to use features like this. Just like in C# and Java how many developers don't ever create a generic class, but they are integral to libraries every developer uses.

  12. seven-phases-max commented on Oct 1, 2015

    @seven-phases-max
    Member
    .my-page
    {
        .page();
        .page-xs-fluid(@page-margin: 8px);
        .page-s-fluid();
        .page-m-fixed();
        .page-l-fixed();
        .page-xl-fixed();
    }

    In Less I suggest this should be:

    .my-page
    {
        .page();
        .page(xs, fluid, @page-margin: 8px);
        .page(s, fluid);
        .page(m, fixed);
    }

    and so on (notice if Bob defines very-large device your library won't have .page-very-large mixins), and you don't need any global variables for this. So for me it yet again seems like it's just the Bootstrap way of implementing grid stuff and mixins is what misdirecting you (BS grid implementation way is a stone age approach forcing predefined set of devices via predefined sets of variables, mixins and so on).

    So no, you did not convince me.

  13. matthew-dean commented on Oct 1, 2015

    @matthew-dean
    Member

    I was also going to suggest keyword guards on mixins as @seven-phases-max. And I would also echo that Bootstrap's way of doing things wasn't what I would call "best practices" for Less code. (I suspect much of the stuff they had to simplify in order to have cross-platform support with Sass.)

    And, having tinkered with building a Less library (which maybe someday I'll finally finish), I can tell you that all of your user goals are possible with Less's existing feature set, just not perhaps in the exact method you're aiming at.

    And, with Less's (unfortunately undocumented) inline, scoped plugins, Framework authors have unparalleled power to build features that don't cause conflicts with other frameworks nor end-user styles, and don't require any extra steps on the part of the user to "install" or "build", unlike extensions for Sass and PostCSS. (See: #2479) So there's a lot of power possible there.

  14. 9 remaining items

  15. seven-phases-max commented on Apr 19, 2017

    @seven-phases-max
    Member

    Renaming the ticket to accommodate both var/mixin cases since they almost always come together as the "Attempting to simulate namespaces and/or parameters via string based manipulation of identifiers" anti-pattern.

  16. changed the title [-]Declare variable with variable name[/-] [+]Interpolation of variable, mixin and function names (a.k.a. "Dynamic" variables/mixins/functions)[/+] on Apr 19, 2017
  17. mchaov commented on Aug 28, 2017

    @mchaov

    I think there is a merit here, although not for dynamic variables. See this example:

    @color-transformation: lighten;
    @some-var: @color-transformation(red, 10%);

  18. rjgotten commented on Aug 28, 2017

    @rjgotten
    Contributor

    @mchaov

    Storing function names inside variables is highly ambiguous. There is no way to discern a keyword from a function name in the parsing phase and the presence of plugins and plugged in functions makes it highly problematic during the evaluation phase as well.

    Your particular case will eventually be covered by mixins being able to return values and being able to be passed by reference, like detached rulesets. The pairing of those two features would give Less the ability to create lambdas.

    A possible future syntax for that might be:

    .some-mixin(@color-transform) {
      @some-var : @color-transform(red);
    }
    
    // ...
    
    .color-transform(@color) : @return {
      @return : lighten(@color, 10%);
    }
    .some-other-mixin(.color-transform);

    But it's all still being debated and conceptualized.

  19. stale commented on Dec 26, 2017

    @stale

    This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

  20. csergiu commented on Dec 27, 2017

    @csergiu

    If you don't give us the option to create functions like in Sass then at least let us do dynamic variable names, this is so frustrating, I'm trying to write a mixing to calculate my em size based on the font-size in px and I can't return a custom value to be used in multiple places, so for example if I have:

    .something {
      .emSize(20px);
      .emSize2(20px);
      margin: @emSize auto @emSize2;
    }
    

    SO I have to create a duplicated mixin just because I can't have a custom returned variable name? At least give us the ability to create functions that automatically return a value, something like this:

    .something {
      margin: emSize(20px) auto emSize(30px);
    }
    

    I also don't want to write the long version of the property just because it's against the coding style we're using.

  21. seven-phases-max commented on Dec 27, 2017

    @seven-phases-max
    Member

    If you don't give us the option to create functions like in Sass

    You have it for more than 2.5 years by now.

    SO I have to create a duplicated mixin just because I can't have a custom returned variable name?

    What is the point of asking to support a dirty kludge instead of asking to support a proper solution instead?

  22. csergiu commented on Dec 27, 2017

    @csergiu

    You have it for more than 2.5 years by now.

    I was expecting it to be built-in and I didn't know about the plugin, my apologies. I would suggest adding this to the core as it's something that a lot of people are using.

  23. seven-phases-max commented on Dec 27, 2017

    @seven-phases-max
    Member

    For the particular use-case though, I believe the proper solution would be a an arbitrary-unit-conversion-plugin (autoconverting whatever units (incl. virtual) back and forth depending on its settings), so one would simply write something like: margin: 20epx auto 30epx - faster, shorter and times more readable.

  24. rjgotten commented on Dec 27, 2017

    @rjgotten
    Contributor

    Agree with @seven-phases-max
    A custom function with a signature like em-scalar(value, base) seems what you need here, @csergiu.

    Validate that value and base are Dimension nodes with conversion-compatible units -- e.g. mm and cm; pt and px; etc. -- then convert to the same unit; divide to obtain scalar value; change unit to em; and done.

  25. csergiu commented on Dec 28, 2017

    @csergiu

    @rjgotten this is what I ended up with:

    .function-em-size(@size: 16px, @base: 16px) {
      return: unit(@size/@base, em);
    }
    
  26. matthew-dean commented on Jan 1, 2018

    @matthew-dean
    Member

    Closing since there a few solutions suggested.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions