简体   繁体   中英

how to use rails model attributes inside sass?

I want to use a string value (hex) that's submitted through a form as the background-color for a div class.

The form is: <%= f.text_field :backgroundcolor %>

The html is: <div class="bottle"></bottle>

And the css is:

.bottle {
background-color: <%= color.backgroundcolor %>
}

But I just get an invalid css error. How do I use these attributes in the sass? I could use them as inline css, but would prefer not to.

The only way you'd get the result you want is if you persisted the data (stored in the DB).


CSS

If the color var was available from the db, or some other source, you'd be able to call it into the CSS:

#app/assets/stylesheets/application.sass
.bottle
   background-color: <%= Option.find_by(title: "color").value %>

This will give you access to the value stored in our fictitious model... however, it would not update on the fly (IE form submit).

Whenever you push your code to "production", Rails will expect to "precompile" the assets.

Precompilation is where all the assets are concatenated into single files (typically application.css ). This process makes your assets static . Indeed, SASS / SCSS are just preprocessors for this process (they run before the minifier).

Whilst you can make your assets dynamic in production (as they are in dev), it drastically slows down your web app (it has to compile the assets for EACH call).

--

To resolve your issue, you'd best put your custom styling either into the <head> of the page, or inline on one of the elements:

#app/views/layouts/application.html.erb
<head>
  <style>
    .bottle { background-color: "<%= Color.find_by(name: 'bottle').value %>" }
  </style>
</head>

...or...

<%= content_tag :div, style: "background-color: #{color.background-color}" %>

No, I don't like it either, but if you want dynamic values, that's what would have to be done. There are some alternatives, but you'll have to hack them together from the backend.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM