0

I need loop over 400+ Font Awesome icon variables (look at the source) by a "pattern", I mean the pattern is @fa-var-*, i.e. @fa-var-apple, @fa-var-archive and so on.

Purpose is create some custom class like .btn-apple, .btn-archive and using the unicode value inside the variable.

Is this possible in LESS?

gremo
  • 47,186
  • 75
  • 257
  • 421
  • 2
    Did you mean using an array loop like [this](http://codepen.io/hari_shanx/pen/bAJih) or going through that entire variables.less file to pick up all variables present inside it instead of defining an array? – Harry Jul 12 '14 at 05:11
  • 1
    No, not directly. To loop through these classes you'll have to create an explicit list like `@icons: apple, archive, array, etc.;` (though if you really need it it's not that tedious since this can be done by trivial search&replace transform from any suitable FA icons list). – seven-phases-max Jul 12 '14 at 06:46
  • E.g. [like this](https://gist.github.com/seven-phases-max/5a2db101f9b1c18a5e46) and loop through the pairs [like that](http://stackoverflow.com/q/23658087/2712740). If you don't need icon character codes also strip them from the list to simplify your loop. – seven-phases-max Jul 12 '14 at 07:00
  • @seven-phases-max: Thats similar to what I did too. But I guess a round about way would be maybe to use Javascript file reader to read the contents and then somehow get it into LESS because LESS can evaluate JS. But don't think it is worth the effort. – Harry Jul 12 '14 at 07:04
  • Thank you both. My attempt was of course to loop directly, as the variable list may change (new icons added). @Harry can you write an answer I will accept? – gremo Jul 12 '14 at 09:28

1 Answers1

1

You can create multiple classes dynamically by using array loops like below. However, the array list values have to be defined prior hand for the loop to be executed.

@variables: adjust,apple,archive,camera,coffee;

.loop(@varCount) when (@varCount > 0){
  @temp: extract(@variables,@varCount);
  .btn-@{temp}{
    font-family: FontAwesome;
    @varName: "fa-var-@{temp}";
    &:before{content: @@varName};
  }
  .loop(@varCount - 1);
}
.loop(length(@variables));

CodePen Demo

You can also use the "for" snippet that seven-phases-max has provided in this answer. It is very useful. (Unfortunately I could give him only one +1 :D)

Note: This is not to say that direct reading from the file is not possible. Since LESS does support JS evaluation, it can be done by using file reader (or maybe even AJAX request), then using Regex to find patterns and loop over the returned array etc. But it becomes way too complex a function which would become an overkill.

Community
  • 1
  • 1
Harry
  • 87,580
  • 25
  • 202
  • 214