如何在 Rails 中创建动态 CSS?

发布于 2024-09-15 22:58:10 字数 150 浏览 6 评论 0原文

使用 Rails 创建动态 CSS 的最佳/最有效方法是什么?我正在网站上开发一个管理区域,我希望用户能够自定义其个人资料的样式(主要是颜色),这也将被保存。

你会在 css 文件中嵌入 ruby​​ 脚本吗? 您需要更改 css 文件扩展名吗?

谢谢。

what is the best/most efficient way of creating dynamic CSS with Rails. I am developing an admin area on a site, where I would like a user to be able to customize the style of their profiles(Colour mostly), which will also be saved.

Would you just embed ruby script in the css file?
Would you need to change the file extension from css?

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

坠似风落 2024-09-22 22:58:10

在 Rails 3.1 中,您可以让 erb 对样式表进行预处理。

现在,假设您在 app/assets/stylesheets 中有一些名为 dynamic.css.scss.erb 的动态样式(末尾的 .erb 很重要!)。它将由 erb(然后由 Sass)处理,因此可以包含类似“

.some_container {
    <% favorite_tags do |tag, color| %>
    .tag.<%= tag %=> {
        background-color: #<%= color %>;
    }
    <% end %>
}

You can include it like any stylesheet”之类的内容。

它应该有多动态?

但请注意,它只会处理一次,因此如果值发生变化,样式表不会发生变化。

我认为还没有一种超级有效的方法可以让它完全动态化,但仍然可以为所有请求生成 CSS。考虑到这一点,Rails 3.1 中提供了一个帮助程序:

  def style_tag(stylesheet)
    asset = YourApplication::Application.assets[stylesheet]
    clone = asset.class.new(asset.environment, asset.logical_path, asset.pathname, {})
    content_tag("STYLE", clone.body.html_safe, type:"text/css")
  end

使用方法如下:

首先,将上述帮助程序复制到 app/helpers/application_helper.rb 中。

然后,您可以将其包含在您的页面中,如下所示:

<% content_for :head do %>
  <%= style_tag "dynamic.css" %>
<% end %>
The rest of your page.

确保您的布局使用内容 :head。例如,您的 layout/application.html.erb 可能如下所示:

...
<HEAD>
  ....
  <%= yield :head %>
</HEAD>
...

我通过 这篇文章

In Rails 3.1, you can have your stylesheets pre-processed by erb.

Now let's say you have some dynamic styling called dynamic.css.scss.erb (the .erb at the end is important!) in app/assets/stylesheets. It will be processed by erb (and then by Sass), and as such can contain stuff like

.some_container {
    <% favorite_tags do |tag, color| %>
    .tag.<%= tag %=> {
        background-color: #<%= color %>;
    }
    <% end %>
}

You can include it like any stylesheet.

How dynamic should it be?

Note that it will be only processed once, though, so if the values changes, the stylesheet won't.

I don't think there is a super efficient way to do have it completely dynamic yet, but it is still possible to generate the CSS for all requests. With this caveat in mind, here's a helper for that in Rails 3.1:

  def style_tag(stylesheet)
    asset = YourApplication::Application.assets[stylesheet]
    clone = asset.class.new(asset.environment, asset.logical_path, asset.pathname, {})
    content_tag("STYLE", clone.body.html_safe, type:"text/css")
  end

Here's how to use it:

First, copy the above helper in app/helpers/application_helper.rb.

You can then include it in your page as follows:

<% content_for :head do %>
  <%= style_tag "dynamic.css" %>
<% end %>
The rest of your page.

Make sure that your layout uses the content :head. For example, your layout/application.html.erb could look like:

...
<HEAD>
  ....
  <%= yield :head %>
</HEAD>
...

I found this out thanks to this post.

桜花祭 2024-09-22 22:58:10

您可以将 ERB 与 CSS 一起使用,只需在控制器中渲染 css 即可。然而,对于如此大量请求的资源,我不建议每次都生成它。我会将用户样式表存储在 memcached 或 redis 中,并在页面加载时从中调用,而不是每次都重新渲染文件。当他们更新样式时,您可以使缓存过期,只需确保在页面呈现时重建它即可。

You can use ERB with CSS, you just need to render css in the controller. However, for such a heavily requested resource, I do not recommend generating this every time. I would store the users stylesheet in memcached or redis, and recall from it when the page loads, rather than rerendering the file each time. When they update their style, you can expire the cache, just make sure it gets rebuilt when the page renders.

许久 2024-09-22 22:58:10

这些年来已经有了很多发展,我最近想出了如何做这个问题所要求的事情。由于自从有人回答这个问题以来已经有大约 9-10 年了,我想我应该投入 2 美分。

正如其他人所说,将 ruby​​ 代码直接放入 CSS 文件中不是一个好的做法,因此无法完成,因为 CSS 是预编译的并且无法在文件内动态更改......但是,它可以在文件外动态改变!

我需要快速概述 CSS 变量,以防未来的读者不知道如何使用它们。

CSS 在其编码语言中使用了变量,以便更轻松地一次更改大量元素。您将这些变量放在 CSS 文件顶部的 root 部分中。像这样:

:root {
    --primary: #0061f2;
    --secondary: #6900c7;
}

现在,任何时候您想要为元素设置其中一种颜色的样式,您都可以简单地这样放置 var(--variableName)

.btn{
   color: var(--secondary);
   background-color: var(--primary);
}

.h1 {
   color: var(--primary);
}

您可以看到如何更容易地更改root 部分中的变量,从而更改 CSS 中的所有其他实例。

现在介绍动态 Ruby 部分。

在应用程序文件的 部分(或者在本问题中是保存管理员仪表板模板的文件),您需要使用动态变量重新声明 CSS 变量并将它们标记为重要。例如,假设您允许用户为其仪表板选择主要颜色和次要颜色,并将它们存储在用户的个人资料中,名称如下:user.primary_coloruser.secondary_color。您需要将其添加到您的 部分:

<style>
  :root{
    --primary: <%= user.primary_color %> !important;
    --secondary: <%= user.secondary_color %> !important;
  }
</style>

!important 标记将覆盖 CSS 文件中找到的变量,从而动态地允许用户更改 CSS并查看其仪表板并使其保持持久性(因为值保存在其个人资料中)。

我希望这对未来的开发人员有所帮助。

快乐编码!

There has been a lot of development over the years, and I recently figured out how to do what this question is asking. And since it has been about 9-10 years since someone has answered this, I thought that I would put in my 2 cents.

As others have said, it is not good practice, and thus can not be done, to put ruby code directly into the CSS file as the CSS is precompiled and is not able to be dynamically changed within the file.... BUT, it can be dynamically changed outside the file!

I will need to give a quick synopsis of CSS variables in case future readers do not know how to use them.

CSS has the use of variables within its coding language to make it easier to change a lot of elements at one time. You put these variables at the top of the CSS file in a root section. Like this:

:root {
    --primary: #0061f2;
    --secondary: #6900c7;
}

Now, anytime you want to style an element one of those colors, you can simply put var(--variableName) like this:

.btn{
   color: var(--secondary);
   background-color: var(--primary);
}

.h1 {
   color: var(--primary);
}

You can see how it would then be much easier to change the variable in the root section and thus change all other instances within the CSS.

Now for the dynamic Ruby part.

In the <head> section of your application file (or in the case of this question the file that holds the template for the admin's dashboard), you will need to redeclare the CSS variables with your dynamic variables and mark them as important. For example, let's say that you allow your user to choose primary and secondary colors for their dashboard and they are stored in the user's profile called like: user.primary_color and user.secondary_color. You will need to add this to your <head> section:

<style>
  :root{
    --primary: <%= user.primary_color %> !important;
    --secondary: <%= user.secondary_color %> !important;
  }
</style>

This !important tag will override the variables found in the CSS file thus dynamically allowing the user to change the CSS and view of their dashboard and have it remain persistent (as the values are saved in their profile).

I hope that this helps future developers.

Happy Coding!

以为你会在 2024-09-22 22:58:10

目前有很多选项可以在 Rails 中生成动态 CSS。

您可以使用 less css - 是具有额外功能的 CSS 扩展。

Gem Less css for Rails 使用 资产管道

如果您使用 twitter bootstrap,您可以查看 less Rails bootstrap

您还可以使用另一种 CSS 扩展语言 Sass 来生成 CSS。这是一个Saas Rails gem

查看 Rails 中的动态 CSS将 Rails 资源渲染为字符串 博客文章和有关 资产管道

相关SO问题:

Currently there is a lot of options to generate dynamic css in rails.

You can use less css - is an extension to CSS with extra features.

Gem Less css for rails provides integration for Rails projects using the Less stylesheet language in the asset pipeline.

If you are using twitter bootstrap you may check this out less rails bootstrap.

Also you can use one more CSS extension language Sass for generating CSS. Here is a Saas rails gem.

Check out Dynamic CSS in Rails and Render Rails assets to string blog posts and article about Asset Pipeline

Related SO questions:

策马西风 2024-09-22 22:58:10

我刚刚为另一个网站构建了这个。我有一个控制器操作和一个视图,可以从数据库中提取颜色值,然后根据当前用户的帐户呈现自定义的 CSS。为了优化,我使用内置的 Rails 页面缓存,它将副本存储在磁盘上并将其用作静态资产。又好又快。

这是 ERB 代码的示例

#header { background: <%= @colors["Header Stripe Background"] %>; border: 1px solid <%= @colors["Header Stripe Border"] %>; }
#header h1 {color: <%= @colors["Headline Color"] %>; }
#header p a { background: <%= @colors["Control Link Background"] %>; color: <%= @colors["Control Links"] %>;}
#header p a:hover {background: <%= @colors["Control Link Hover"] %>; text-decoration:underline;}

I just built this for another site. I have a controller action and a view that pulls color values out of the database, then renders a customized CSS based on the current user's account. To optimize, I am using the built in Rails page caching, which stores a copy on disk and serves it as a static asset. Nice and fast.

Here's an example from the ERB code

#header { background: <%= @colors["Header Stripe Background"] %>; border: 1px solid <%= @colors["Header Stripe Border"] %>; }
#header h1 {color: <%= @colors["Headline Color"] %>; }
#header p a { background: <%= @colors["Control Link Background"] %>; color: <%= @colors["Control Links"] %>;}
#header p a:hover {background: <%= @colors["Control Link Hover"] %>; text-decoration:underline;}
强辩 2024-09-22 22:58:10

该解决方案在 config/site_settings.rb 中定义了一些常量,然后可以在整个 Rails 应用程序中使用这些常量,并在 Rails 应用程序启动且 CSS 输入文件已修改时自动生成 CSS 文件

。 “http://unixgods.org/~tilo/Ruby/Using_Variables_in_CSS_Files_with_Ruby_on_Rails.html” rel="nofollow">http://unixgods.org/~tilo/Ruby/Using_Variables_in_CSS_Files_with_Ruby_on_Rails.html

This solution defines some constants in config/site_settings.rb, which can then be used throughout the Rails application, as well as for automatically generating the CSS files whenever the Rails app starts and the CSS input files have been modified..

http://unixgods.org/~tilo/Ruby/Using_Variables_in_CSS_Files_with_Ruby_on_Rails.html

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文