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

Revolutionizing Interaction: Unveiling the Power of Bootstrap 3

Would you be able to assist me in customizing buttons to resemble a typical dropdown link? <div class="dropdown"> <button class="btn dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown">Dropdown <span class="caret"&g ...

Implement jQuery to dynamically assign an "Active" class to tab elements based on the current page being loaded

INQUIRIES I have include: How do I apply a class to an element using jQuery, or any other method, for the active tab? Ensure that the dropdown tab appearing is the one containing the active tab, not always the Company one. In essence, I want the ac ...

The stacking order of a child element within a parent element, which has a transform

Hey there, I've encountered a problem and was wondering if you could assist me with it. In the code snippet provided below, you'll see that there are elements with: transform: translate(0,0); Within these elements, there is a "dropdown" elemen ...

What methods can I use to ensure my HTML/CSS code is compatible with all browsers? It functions properly on Chrome but encounters issues on Safari, Edge, and other

My hosting for the website is with bluehost, and interestingly when viewed on Chrome, everything appears perfect. However, upon switching to Safari, I noticed that the background of the about me section is not black as intended, and the footer seems to be ...

Display an HTML code snippet on the webpage

I'm facing a situation that has been discussed before on this platform. However, I want to present my problem in a different light. I am working with PHP and need to display an HTML string from the database on my webpage. The issue is that the CSS app ...

Retrieve the background color using code-behind

Despite its humorous appearance, I am having trouble with the Syntax :( I have a background color in my code behind file and need to correct the syntax here so that my Table displays the correct background color: <Table style="background-color:" &apos ...

Learn how to utilize ng-class to assign an ID selector to HTML elements

In my code, I have an icon that is displayed conditionally using ng-class. I am looking to include ID's for both the HTML elements. <i ng-show="ctrl.data.length > 1" ng-class="{'glyphicon glyphicon-chevron-down': !ctrl.isOpen, ...

The appearance of Google Font CSS may vary when retrieved using WGET

Uncovering an issue while attempting to dynamically fetch a Google Fonts css file to extract the font URL. The scenario looks like this: (Viewed in Chrome) Contrast that with: WGET -qO- http://fonts.googleapis.com/css?family=Droid+Sans Upon inspecti ...

What is the best way to create a sliding animation on a div that makes it disappear?

While I may not be an expert in animations, I have a question about sliding up the "gl_banner" div after a short delay and having the content below it move back to its original position. What CSS properties should I use for this animation? Should I use css ...

Issue with border radius in MUI 5 affecting table body and footer elements

Currently, I am diving into a new project utilizing React version 18.2 and MUI 5.10.3 library. My main task involves designing a table with specific styles within one of the components. The table header should not display any border lines. The table body ...

When the collapse button is clicked, I aim to increase the top value by 100. Subsequently, upon a second click, the top value should

https://i.stack.imgur.com/p9owU.jpghttps://i.stack.imgur.com/Kwtnh.jpg I attempted to utilize jQuery toggle, but unfortunately, it is not functioning as expected. <script> $(document).ready(function () { $(".sidebar ul li&quo ...

Transforming the navigation menu using CSS, HTML, and jQuery

One challenge I am facing involves creating a menu similar to the one on http://edition.cnn.com/. I want the clicked button in the menu to receive focus, while the others lose it. Despite trying various methods, I have not been successful. Can someone off ...

Learn how to use the CSS transform-scale() function to scale text independently from its container while maintaining proper alignment

I am currently working on adjusting font sizes to match another one, but I am facing an issue where the container's size is also being affected, resulting in misalignments. I have experimented with different display types (block, inline) and even trie ...

Displaying or concealing dropdown menus based on a selected option

My goal is to have a drop-down menu in which selecting an option triggers the display of another drop-down menu. For example, if I have options like "Vancouver," "Singapore," and "New York," selecting Vancouver will reveal a second set of options, while ch ...

The URL "http://packagist.org/p/provider-3.json" was unable to be retrieved due to a bad request error (HTTP/1.1 400 Bad Request)

Encountering a 400 bad request issue when trying to connect over HTTP, despite the package only being installable via HTTP. Attempting to override in composer.json to force HTTPS as suggested by others for a workaround, but that solution doesn't seem ...

Struggling to keep the footer anchored at the bottom of the page

When the content on an HTML page is minimal, the footer may end up positioned halfway up the page, creating a blank space below. This can be unappealing, especially on larger screens. Designers are frequently tasked with moving footers to the bottom of the ...

Maintain font kerning for span elements that are not displayed inline

I am looking to add some transform effects to individual letters in a word. To achieve this, I have enclosed each letter within a span element. However, when setting the display of these spans to inline-block, the font kerning gets disrupted. I have exper ...

How can we stop Vuetify from overwriting Bootstrap3's classes when using treeshaking?

I am currently in the process of transitioning an app from jQuery/Bootstrap3 to Vue/Vuetify. My approach is to tackle one small task at a time, such as converting the Navbar into its own Vue component and then gradually updating other widgets. Since the n ...

Distribute the elements evenly between two separate divs

Hello everyone! I have a unique challenge that I hope someone can help me with. I have a list of links to various tests, but different sections require these links to be displayed in different ways. One section needs them spread over two columns, while an ...

The mobile page is refusing to scroll, causing all the text to bunch up at the top of the screen

After learning HTML/CSS/Js/PhP over a few months, I recently completed my first website. I am facing an issue with one of the pages on my website when viewed on a mobile device. The parallax scrolling header image does not scroll either horizontally or ve ...