How to create dynamic CSS based on user input

The user should be able to design a room (model number) in my Rails application. When a user visits myapp.com/room/1 , a room is displayed with its content and specific design.

The design or CSS of the room is based on the parameters of the room (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 create specific CSS for each room. When a user visits myapp.com/room/1 , my application must create specific CSS (or SCSS) for room1. Where (which controller) should I build this CSS?

thanks

+5
source share
2 answers

You can make your RoomsController also a CSS response to make this 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 visualization template for the CSS format:

 /* app/views/rooms/show.css.erb */ .room { background-color: <%= @room.color1 %>; color: <%= @room.color2 %>; } 

Please note that this is very similar to a regular template. You have to make sure that this will result in valid CSS.

You need to make sure the stylesheet is enabled when the user visits the page. Say a user can view their room design when they visit /rooms/1 . This will create an HTML template that 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> 

Note that I used content_for around the style sheet link tag. We can use this to make sure the style sheet link tag displays well in the layout head:

 <!-- app/views/layouts/application.html.erb --> <head> <%= yield :stylesheet_includes %> </head> 

Of course, you will need to fill in the details yourself, but this will be the most logical approach to the problem.

+13
source

If you create your controller to respond to the show action with json requests, you can get the attributes of the Room object in json format

http://localhost.com:3000/rooms/1.json

{"id":1,"color1":"black","color2":"green","created_at":"2014-12-15T19:52:21.235Z","updated_at":"2014-12-15T19:52:21.235Z"}

In this case, you can use javascript to get the request , get the data in JSON and subsequently use this data to control the house.

$.get( "rooms/1.json", function( data ) { alert(data); });

0
source

Source: https://habr.com/ru/post/1208898/


All Articles