Utilizing SASS for customizable color schemes

I am in the process of creating a website using Rails 3 which will allow users to customize their profiles with different layouts and color schemes. I have already implemented SASS, and I believe it would be incredibly useful if I could achieve something like this…

<link src="base_styles.css" rel="stylesheet">
<link src="color_schemes/users_choice.css" rel="stylesheet">
<link src="layouts/users_choice.css" rel="stylesheet">

…where the color scheme details would mainly (if not entirely) consist of SASS variables specifying the colors to be used in the layout. Of course, I cannot simply link the SASS or CSS files in this way; I would need to import them into SASS.

Is there a way to dynamically import SASS files into the parser at request-time and then cache the resulting CSS files for future use?

I have considered the less optimal option of pre-building every possible combination upon deployment, but that approach falls short if I want to offer users the ability to set their own colors down the line. It feels like a missed opportunity with SASS, as though it should be possible to implement such functionality seamlessly.

Answer №1

After delving into the Sass documentation, it appears that achieving this task is indeed possible using their functions. However, it seems like a complex route to take and could lead to potential issues down the line.

The most effective way I've discovered to tackle this issue is by generating the user-specific template when they update their settings. This approach not only works more efficiently but also ensures that no requests are delayed while waiting for parsing.

# unless cached_copy_exists
template = %Q{
  @import '/path/to/color_scheme';
  @import '/path/to/layout';
}

output = Sass::Engine.new(template, :syntax => :scss).render

# output rendered CSS to file for inclusion in HTML template

To allow for custom colors, user-input can be compiled into SASS css variables in a string and added to the template file passed to the Sass parsing/rendering engine.

Update:

As per request, here's a detailed example demonstrating how this method functions, focusing specifically on utilizing Sass variables and a pre-designed Sass stylesheet (simplified for clarity):

# config/routes.rb
resources :stylesheets, only: [:show]

# app/controllers/stylesheets_controller.rb
class StylesheetsController < ApplicationController
  layout nil

  def show
    styles = Stylesheet.find(params[:id])
    base_stylesheet_path = Rails.root.join('app', 'assets', 'profile.scss')

    # Constructing the SCSS string for the Sass rendering engine
    @sass = <<-SASS
      #{styles.to_sass}
      @import "#{base_stylesheet_path}";
    SASS

    # Cache set for long term
    response.headers['Cache-Control'] = "public, max-age=#{1.year}"

    respond_to do |format|
      format.css
    end
  end
end

# app/views/stylesheets/show.css.erb
<%= raw Sass::Engine.new(@sass :syntax => :scss).render -%>

# app/models/stylesheet.rb
class Stylesheet < ActiveRecord::Base
  serialize :variables, JSON

  def to_sass
    # Converting variable hash into SCSS
    variables.each_pair.map do |name, value|
      "$#{name}: #{value};"
    end.join("\n")
  end
end

# Example for the stylesheet model 
stylesheet = Stylesheet.new
stylesheet.variables[:primary_color] = "#0000ff"
stylesheet.save   

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

Hover image displacement

Can anyone help me identify the feature used in this price list where the mouseover changes and a big image appears underneath? I'm trying to achieve something similar but can't figure out how. Any guidance would be appreciated. ...

Does the downloading of images get affected when the CSS file has the disabled attribute?

Is it possible to delay the download of images on a website by setting the stylesheet to 'disabled'? For example: <link id="imagesCSS" rel="stylesheet" type="text/css" href="images.css" disabled> My idea is to enable the link later to tri ...

What is the best way to apply a hover rule to a CSS class in order to change the color of a specific row when hovering in

I have managed to successfully apply a classname and add color to a specific row in my react-table. However, I am facing difficulty in adding a hover rule to this className to change the color when I hover over the row. Can someone guide me on how to apply ...

The text field is being styled with inline styles automatically

I am trying to set a custom width for a textarea in my form, but the inline styles are automatically overriding my CSS. I have checked my scripts, but I am unsure which one is manipulating the DOM. If you have any insight, please let me know. This is the ...

Troubleshooting issues with the Bootstrap dropdown menu

I am struggling to get a dropdown menu working properly with Bootstrap. Despite looking through similar questions on this forum, I have not yet found a solution that works for me. Below is the HTML head section of my code: <!DOCTYPE html PUBLIC '- ...

Step-by-step guide on creating a blank horizontal line in an HTML table

Can anyone help me figure out how to draw a horizontal line connecting from td 1 to td 4 without relying on content CSS? I'm envisioning a progress bar like the one shown in the following image: https://i.sstatic.net/on8Bi.png <table> < ...

tips for incorporating margin without sacrificing responsiveness

Having an issue with three cards in a row, they are too close together without any margin. It doesn't look good, so I tried adding margin, but it messes up the responsiveness that Bootstrap provides. So, I decided to add padding only. Any suggestions ...

Steps for creating a resizable and automatically hiding side menu

I am working on a side menu that can be resized, and I want it to collapse (set to zero width) when it is empty. I have considered implementing one of these features individually, but I'm not sure how to make both work together. Is there a way to ad ...

How can you vertically center an icon button in Material UI?

Looking for help with aligning elements in this code snippet: <TextField id="outlined-basic" label="22Keyword" defaultValue={"test123"} variant="outlined" /> <IconButton aria-label="delete&q ...

Ensuring Consistent Vertical Spacing for CSS-Animated Bootstrap 5 Navbar Toggler Buttons in All Browsers

After watching a tutorial on implementing a custom Navbar toggler button in Bootstrap 5, I decided to try it out myself. However, I encountered an issue with the spacing between the three bars that make up the toggler button - the spacing looked different ...

AngularJS flip card animation

Exploring the new AngularJS method for animations during page transitions, I am keen on integrating a card flip effect (resembling http://jsfiddle.net/nicooprat/GDdtS/) body { background: #ccc; } .flip { -webkit-perspective: 800; width: 400px; height: ...

fluid columns gliding from side to side

I'm currently working with Bootstrap to design responsive columns. My goal is to have the next column of content slide in from either the left or right side when the user clicks on the respective arrow button. While I have found solutions for fixed w ...

Arranging Bootstrap Cards in an Orderly Stack

I recently created a set of bootstrap cards displayed like this: <div class="card-deck"> <div class="card"> <img class="card-img-top" src=".." alt="Card image cap"> <div class="card-body"> <h5 cl ...

The chosen color for the link button in CSS

PHP CODE : $getOID=$_GET["id"]; for($i=$getOID-($getOID-1); $i<=5;$i++){ echo '<a class="current" href="postlogin.php?id='.$i.'">'.$i.'</a>'; } CSS STYLING FOR BUTTONS : .pagging { height:20px; ...

Click on the link that surrounds an inline-block span in Internet Explorer

In Chrome and Firefox, the following code works fine and makes the container clickable. However, in Internet Explorer, only the inner div changes the cursor to indicate that it's clickable, not the span. I could use cursor:pointer to fix this issue, ...

Tips for expanding the maximum width of a container using bootstrap4

Having trouble increasing the maximum width of my container. How can I adjust the width in the source code? I've attempted changing the width size in the bootstrap-grid.css file. The Element Inspector lets me change the max-width. Any tips on modify ...

Dropdown Box Linking and Input Field Integration in HTML

I have a scenario where students need to pay monthly fees for their classes. My objective is as follows: 1. Dropdown #1: Student Names 2. Dropdown #2: Month Names 3. Textbox: Fees amount for the selected month The code I am using: $(document).ready(fu ...

Creating a PHP-enabled HTML button that spans multiple lines

Currently, I am working on creating a list of buttons with h5 text. The issue I'm facing is that all the buttons have the same width, but when the text exceeds this width, the button expands. I would like the text to span multiple lines without affect ...

Aligning text to the right in Bootstrap 5 input fields

I'm trying to align the values of my inputs to the right. Any suggestions on how to achieve this? Here's a visual representation of what I'm looking for. This is the snippet from my code: <td style="text-align:center; vertical-alig ...

Issue with border spacing functionality

I'm having some difficulty with my border spacing in CSS. No matter what size I specify, it doesn't seem to have any effect. I just want to use a border for the top line. Here is my CSS: p { border-spacing: 5000px; text-align: right; ...