LESS: Using variable values in mixin and variable names

I am looking to simplify the process of generating icons from svg-files while also creating a png-sprite fallback for IE8 support. I am using grunt.js and less.

I was inspired by the implementation on 2gis.ru: (in Russian), where they used technologies such as node.js, npm, grunt.js, and less.

Here is a snippet of code that showcases what I am aiming to achieve:

I have created this template: https://github.com/andrey-hohlov/template-mark-up (don't forget to use 'npm install' after cloning)

However, I am facing an issue in one step:

  1. Place svg-icons in github.com/andrey-hohlov/template-mark-up/tree/master/assets/dev/img/svg-icons
  2. Put png-icons in github.com/andrey-hohlov/template-mark-up/tree/master/assets/dev/img/png-icons
  3. Utilize grunt
  4. All sprites will be generated in github.com/andrey-hohlov/template-mark-up/tree/master/assets/build/img
  5. .less files are created in github.com/andrey-hohlov/template-mark-up/tree/master/assets/dev/css/less/mixins/bg-icon/temp using spritesmith, which cannot be modified

Now onto the less files:

  1. github.com/andrey-hohlov/template-mark-up/blob/master/assets/dev/css/less/mixins/bg-icon/temp/datauri.less contains base64 code for svg icons with class names based on file names, only allowing me to set suffixes and prefixes
  2. Files like github.com/andrey-hohlov/template-mark-up/blob/master/assets/dev/css/less/mixins/bg-icon/temp/sprite.datauri.less include mixins and variables for creating sprite css for png icons, leveraging the width and height data from svg icons (as the datauri task provides only base64)
  3. The issue lies in github.com/andrey-hohlov/template-mark-up/blob/master/assets/dev/css/less/mixins/bg-icon/bg-icon.less. There are two mixins - one for svg icons and one for png icons. I need to utilize them with the "filename" parameter to generate css for icons, but I am unsure how to do so. I have left comments in the file.

P.S. I had to remove some URLs due to my lack of reputation. P.P.S. Apologies for any language errors in my explanation :(

Answer №1

Alright.

I am curious about how I can utilize mixin names and variable names based on another variable's value.

Therefore:

(1). If you want to reference a variable by its name stored in another variable, you can use the syntax for "Variable Referencing", like this:

#example {
    @banana: 22px;
    @potato: "banana";

    width: @@potato; // -> 22px
}

(2). Calling a mixin by a name set in a variable is not possible. To selectively invoke a mixin based on a variable value, consider using "Pattern Matching". Here’s an example:

.mixin("banana", @values...) {
    color: @values;
}

.mixin("potato", @values...) {
    background-color: @values;
}

#usage {
    .mixin("banana", tomato); // -> color: #ff6347
    .mixin("potato", wheat);  // -> background-color: #f5deb3
}

If modifying those mixins is not an option, one alternative is to create wrappers:

.mixin(peach) {.mixin-peach()}

#usage {
    @variable: peach;
    .mixin(@variable); // invokes .mixin-peach
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The web forms on my shared hosting account are set up to send emails via SMTP to my designated email address, but they are unable to send to providers such as Gmail

After conducting a search, I am still struggling to find the right solution... I have encountered an issue with setting up web forms using Node.js (express) and PHP. The problem lies in sending form data to email addresses outside of my domain. Despite su ...

How do I incorporate a jcarousel slider into a thickbox popup using jQuery, HTML, and CSS?

I'm attempting to incorporate a dynamic car carousel slider into a popup that opens with Thickbox. I've made numerous attempts but haven't achieved success yet. It works when called directly in HTML, but doesn't function properly when ...

Update the function to be contained in a distinct JavaScript file - incorporating AJAX, HTML, and MySQL

Currently, I am working on a project and need to showcase a table from MySQL on an HTML page. The JavaScript function in my code is responsible for this task, but due to the Framework 7 requirement, I must separate the function into a different .js file ra ...

Encountered an issue with mapping data from a controller to a view in Angular.js

Currently, my application consists of only three small parts: a service that makes an http call to a .json file, a controller that receives data from the service and sends it to a view. Everything was working fine when I hard coded the data in my service. ...

Trouble with npm installation on Windows following node update

After updating my Node.JS last night, my npm install function stopped working. I tried uninstalling and reinstalling Node, but it didn't solve the issue. My system is running on Windows 8.1 with Node version 8.9.4 and NPM version 3.3.12. The error mes ...

Challenges with Dual Y-Axis in a Horizontal Stacked Bar Graph

My charts are presenting me with several issues and questions: Is there a way to avoid the right y-axis tick values from either being partially erased or overlapping with the chart? When I set yValuesTripId as the domain for both the left and right y ...

Transitioning from curl to jQuery's $.ajax() method

Recently, I encountered a challenge while trying to switch the curl code used for an API known as TextRazor to jquery's AJAX due to certain limitations on the platform. Despite exploring various solutions suggested by the community in response to simi ...

Generate a dynamic image using CSS and either a div or a span tag

My image is intricately carved into several slices. You can view it here <!--Force IE6 into quirks mode with this comment tag--> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.d ...

HTTP / HTTPS GET Request Alexa Skill - "The result is not valid" Lambda Reply

Currently, I am in the process of developing an Alexa skill that assists users in finding the nearest Kaiser Permanente hospital, clinic, or pharmacy. During testing, if one of the three specific keywords is used, I encounter an error message: The response ...

Issues with saving data to MongoDB using NodeJS, ExpressJS, and EJS database connection

I am in the process of developing a childcare management web application using NodeJS with ExpressJS, mongoose, and EJS. The application features a module for adding participants and another module to track each participant's daily meal count four tim ...

Puppeteer - Issue with Opening Calendar Widget

Problem: Unable to interact with the calendar widget on a hotel website (). Error Message: Node is either not clickable or not an Element Steps Taken (code snippet below): const puppeteer = require('puppeteer') const fs = require('fs/promi ...

Issue arises after injecting HTML element into the DOM due to memory constraints and display inconsistencies

Upon executing the following script in Firefox... var d = $("<div class='test'></div>"); d.hide(); $("body").prepend(d); d.show(); ...and examining the HTML, the inserted element will have the style attribute: style="display: blo ...

New issue with installing npm cra

Recently updated to npm version 6.14.4 and encountered an issue while trying to create a new app with cra-template. How can I resolve this problem? npx create-react-app sphinx.ui.react Error Log 50 timing stage:runTopLevelLifecycles Completed in 5234ms ...

Executing testing using the npm command line

Currently, I have two distinct test suites - regular tests and coverage tests. As of now, I am configuring one to run with npm test and the other with npm start: "scripts": { "test": "node scripts/run-truffle-tests.js", "start": "node scripts/r ...

Is there a way to transform a time string, for instance "8:02 AM", into a sortable field?

I am currently working with a MongoDB database that stores times as strings, and I want to filter queries based on specific time ranges. For instance, the time fields in my database are formatted as "8:02 AM" and "10:20 PM", and I am looking to refine my ...

"Uncovering the dangers of XMLHttpRequest: How automatic web-page refresh can lead

Hello, I have been developing a web interface for some hardware that utilizes an 8-bit microcontroller. The webpage includes HTML, JavaScript, JSON, and XHR (XMLHttpRequest) for communication purposes. My goal is to create a page that updates every 250 ...

Encountering an issue with running the React Application due to an error when

I've been trying to launch my React app in a local environment but I keep encountering the following error PS npm start npm ERR! code ENOENT npm ERR! syscall open npm ERR! path C:\Documents\business-website-react-master\package.json np ...

Attempting to implement usedispatch hook in combination with userefs, however, encountering issues with functionality

I've been exploring the Redux useDispatch hook lately. I created a simple app for taking notes in a todo list format. However, I am facing an issue with useDispatch as it's not working for me and I keep encountering this error: Module build faile ...

Can you explain the contrast between uploading files with FileReader versus FormData?

When it comes to uploading files using Ajax (XHR2), there are two different approaches available. The first method involves reading the file content as an array buffer or a binary string and then streaming it using the XHR send method, like demonstrated he ...

The lengthy email exceeds its limits

Take a look at this code snippet: <div className='mt-[3vh] flex h-1/3 min-h-fit w-[80%] min-w-[300px] flex-col content-center items-center justify-center rounded-2xl bg-white shadow-[0_0_8px_rgba(0,0,0,0.2)]'> {user?.image && ...