Reputation: 109
On our Website we have a section with multiple sites who all uses different color codes. I would like to keep it simple and change the color on a specific value inside a data-attribute, like this:
[data-page-id="site1"] {
@color: #F00;
}
[data-page-id="site2"] {
@color: #D40;
}
.page-title {
color: @color;
}
.page-content {
background: @color;
}
My approach gives me an error, but is there a smiliar method to do this?
Upvotes: 1
Views: 52
Reputation: 89750
When the Less compiler is compiling your code, it would not have any idea of the data attribute that is present in your markup (as Less is compiled separately from your HTML). Hence, you cannot determine the value of the color variable depending on the attribute's value.
You could try and compile your Less code on the client-side but that is not really recommended (even by the official Less website) for production sites. It is better used only for some testing.
Assuming the data-page-id
attribute is present in the element that is the parent of the .page-title
and .page-content
, you could use something like below to statically generate the required rulesets.
@site-colors: #F00, #D40;
[data-page-id="site1"] {
.page-title {
color: extract(@site-colors, 1);
}
.page-content {
background: extract(@site-colors, 1);
}
}
[data-page-id="site2"] {
.page-title {
color: extract(@site-colors, 2);
}
.page-content {
background: extract(@site-colors, 2);
}
}
[data-page-id="site1"] .page-title {
color: #ff0000;
}
[data-page-id="site1"] .page-content {
background: #ff0000;
}
[data-page-id="site2"] .page-title {
color: #dd4400;
}
[data-page-id="site2"] .page-content {
background: #dd4400;
}
<div data-page-id="site1">
<div class="page-title">Site 1 Title</div>
<div class="page-content">Site 1 Content</div>
</div>
<div data-page-id="site2">
<div class="page-title">Site 2 Title</div>
<div class="page-content">Site 2 Content</div>
</div>
If you have many such data-page-id
values then you could also make use of a loop to avoid writing the same piece of code multiple times.
Or alternately, you can write one common less file for the common rules applicable for all pages (like below) and one site specific file which will have the @color
variables' value and then import the common file.
/* settings.less - common settings */
.page-title {
color: @color;
}
.page-content {
background: @color;
}
/* site specific file - site1.less*/
@import settings.less;
@color: #f00;
Upvotes: 2