A user should be able to design a room (room is a model) in my Rails app. When the user visits myapp.com/room/1
the room with its content and specific design is shown.
The design or CSS of the room is based on room parameters (color1, color2, ...) and some random generated design characteristics (font type, image border, ...). These characteristics are stored in the room model when the room is saved.
I don't see how I can generate a specific CSS for each room. When the user visits myapp.com/room/1
my app should build specific CSS (or SCSS) for room1. Where (what controller) should I build that CSS?
Thanks
color = "red"; you can apply the style change dynamically. Below is a function that turns an element's colour to red when you pass it the element's id . You could also use setAttribute(key, value) to set a style on an element. For example, you could set the colour of an element to red by calling element.
It is worth noting that while pre/postprocessor variables are only used at compilation-time, CSS variables can be used and updated dynamically. What does this mean? It means that they are preserved in the actual CSS stylesheet. So the notion that they are variables will remain even after the stylesheets are compiled.
To add CSS properties dynamically, we use css() method. The css() method is used to change style property of the selected element.
You can make your RoomsController
respond to the CSS format as well in order to get this to work:
# app/controllers/rooms_controller.rb
class RoomsController
def show
@room = Room.find(params[:id])
respond_to do |format|
format.html
format.css
end
end
end
Then you need to implement a template to be rendered for the CSS format:
/* app/views/rooms/show.css.erb */
.room {
background-color: <%= @room.color1 %>;
color: <%= @room.color2 %>;
}
Note how this is very similar to a regular template. You need to make sure that this results in valid CSS.
You need to make sure the stylesheet is included when the user visits the page. Let's say a user can browse their room design when they visit /rooms/1
. This will render a HTML template, which we could define as follows:
<!-- app/views/rooms/show.html.erb -->
<% content_for :stylesheet_includes do %>
<%= stylesheet_link_tag(room_path(@room, format: :css)) %>
<% end %>
<div class="room">
Room Contents Here
</div>
Notice that I've used content_for
around the stylesheet link tag. We can use this to make sure the stylesheet link tag is rendered nicely in the head of the layout:
<!-- app/views/layouts/application.html.erb -->
<head>
<%= yield :stylesheet_includes %>
</head>
Of course you'll need to fill in the details yourself, but this would be the most logical approach for the problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With