0

Currently, one of my developers have developed this less file:

.countryFlag( @countryName :"DK"){
    content: url("/images/flags/@{countryName}.gif") no-repeat center;
}

a.flag-DK {
    .countryFlag ();
}

a.flag-DE {
    .countryFlag (DE);
}

a.flag-EE {
    .countryFlag (EE);
}

...

with some 20 countries. I was wondering if this can be done smarter with less, either using loops or dynamic names created at runtime. Consider the following pseudo-code that describes what I want:

a.flag-@{country} {
  content: url("/images/flags/@{country}.gif") no-repeat center;
}

that simply matches any definitions. I am aware that this could create lots of conflicts, but perhaps it could be further narrowed down via regex? Makes sense, but haven't been able to find this.

An alternative could be to create the "static" css classes using a loop of some sort. Consider this pseudo-alternative:

@countries: 'dk', 'de', 'uk', 'us', ...;

for(country : countries) {
    a.flag-@{country} {
        content: url("/images/flags/@{country}.gif") no-repeat center;
    }
}

and thus create the classes for a pre-determined list of countries.

Is either of these alternatives available in some sort of way? Or can you perhaps advice on a third option that I might have overlooked? I feel kinda stupid when I see 20-something almost identical classes defined, having only a small string in difference, and think that a CSS pre-processor MUST be able to do this smarter.

Thanks!

kllund
  • 1
  • 2
  • You'll find a nice answer [here](http://stackoverflow.com/questions/21440789/loop-through-array-of-values-in-less). – Andrea Carraro Jul 08 '14 at 08:00
  • I saw this before I posted, but unfortunately, it doesn't solve my issue, as I would need to grab the country definition from the class name in order to achieve what I am after.Thanks though :) – kllund Jul 08 '14 at 08:13
  • The other example assumes that a bunch of variables are pre-defined. I would need the iteration of the array to assume the values defined in my list of arguments (@countries), and not to interpret them as variable names. – kllund Jul 08 '14 at 08:14
  • See http://stackoverflow.com/q/23249214/2712740. But yes, as @toomuchdesign suggested the "icon" example in [`[1]`](https://github.com/seven-phases-max/less.curious/blob/master/articles/for-each.md#practical-examples) is even closer to what you need. – seven-phases-max Jul 08 '14 at 10:44

1 Answers1

1

Less.js "for" snippet has a few lines of documentation, too. I found this page very useful a few days ago when I was facing a problem like yours.

You can simply declare a list of values to be used as strings in your foreach loop. (eg @list: banana, apple, pear, potato, carrot, peach;)

Make you sure you're using a recent version of Less!

Andrea Carraro
  • 9,731
  • 5
  • 33
  • 57