Sass,根据数据动态创建css类

Sass,根据数据动态创建css类,sass,Sass,我有这门课: .currency-flag-clp:before { background-image: url('~currency-flags/dist/square-flags/clp.svg'); } 我想将该类动态添加到html元素中,因此需要添加一个类,如: .currency-flag-XXXXX:before { background-image: url('~currency-flags/dist/square-flags/XXXXX.svg'); } sa

我有这门课:

.currency-flag-clp:before {
    background-image: url('~currency-flags/dist/square-flags/clp.svg');
}
我想将该类动态添加到html元素中,因此需要添加一个类,如:

.currency-flag-XXXXX:before {
    background-image: url('~currency-flags/dist/square-flags/XXXXX.svg');
}

sass有没有办法做到这一点?我不想为每个值定义270类,我只想根据我的数据创建类。

当您想在元素上设置单个类时,您似乎可以在构建页面时访问货币数据。在这种情况下,可能会有一种没有SASS的更简单的替代方法

(1)替代(非SASS)解决方案-可能是一种更简单的方法

(a) 根据实际用户设置/货币,将实际标志图像的css变量“实际货币标志url”写入文件头部的样式块中

(b) 然后使用该变量在css中构建url路径

// add to <head> of page:
// based on your data maybe you can do it by php
// note: don't use slashes when building url(...)

<style>
   :root { 
      --actual-currency-url: url(url-path/flag-[actualCurrency].jpg);
   }
</style>


// change class off html element
// from <div class="currency-flag-XXXXX"> to:

<div class="currency-flag">

// now you can do in your separate stylesheet file:
.currency-flag:before {
  background-image: var(--actual-currency-url);
}

// example code in SASS:

$flag-suffixes: (
    USD,
    AUD,
    EUR,
    //...
);

@each $suffix in $flag-suffixes {

    .currency-flag-#{$suffix}:before {
        background-image: url('~currency-flags/dist/square-flags/#{$suffix}.svg');
    }
}