Skip to content

Commit 06c6922

Browse files
committed
Update article content
1 parent 95cbfeb commit 06c6922

File tree

1 file changed

+19
-3
lines changed

1 file changed

+19
-3
lines changed

app/content/pages/articles/how-to-render-css-dynamically-in-rails.html.mdrb

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -84,13 +84,29 @@ The partial that renders CSS in the HTML response looks something like this:
8484

8585
The controller helper method `custom_color_scheme?` looks for the presence of a color scheme id in `params` or the `session` and `find_color_scheme` makes a database query to find a `ColorScheme` record if needed.
8686

87-
`ColorSchemes::Css` is a simple [Phlex](https://www.phlex.fun/) component but it could easily be rendered in an ERB partial. Here‘s what it looks like:
87+
`ColorSchemes::Css` is a simple [Phlex](https://www.phlex.fun/) component. Here‘s what it looks like:
8888

8989
<%= render CodeBlock::AppFile.new("app/views/components/color_schemes/css.rb", language: "ruby") %>
9090

91-
Phlex is a Ruby gem for building object-oriented HTML components. It‘s an alternative to ERB templates. Phlex isn‘t a requirement for dynamic CSS but suits my preferences in this case.
91+
Phlex is a Ruby gem for building object-oriented HTML components. It‘s an alternative to ERB templates. Phlex suits my preferences in this case, but it isn‘t a requirement for dynamic CSS. You could easily write this in an ERB template instead. It might look something like this:
92+
93+
```erb
94+
<%
95+
color_name = @color_scheme.name.parameterize
96+
# #to_hsla defined as a helper method
97+
%>
98+
<style>
99+
:root {
100+
<%= @color_scheme.weights.map { |weight, color| "--color-#{color_name}-#{weight}: #{to_hsla(color)};" }.join("\n\s\s") %>
101+
102+
<% if @my_theme %>
103+
<%= @color_scheme.weights.map { |weight, color| "--my-color-#{weight}: var(--color-#{color_name}-#{weight});" }.join("\n\s\s") %>
104+
<% end %>
105+
}
106+
</style>
107+
```
92108

93-
The key point here is that we can use logic in Rails templates or components for rendering key bits of dynamic CSS at the time of the request, just as you can for HTML.
109+
The key point here is that we can use logic in Rails templates or components for rendering key bits of dynamic CSS at the time of the request, just as you can for HTML. When combined with Hotwire, this enables server-driven interactive styles like my color scheme preview.
94110

95111
## Controller actions aren’t just for HTML either
96112

0 commit comments

Comments
 (0)