Skip to content

Commit 22faa70

Browse files
committed
Update article content
1 parent 81bf174 commit 22faa70

File tree

1 file changed

+10
-1
lines changed

1 file changed

+10
-1
lines changed

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

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -180,7 +180,7 @@ We can use this endpoint in a stylesheet `<link>` tag just like any other static
180180
<%= stylesheet_link_tag color_scheme_path(@color_scheme, format: :css) %>
181181
```
182182

183-
A downside of moving our dynamic CSS to a separate controller action is that it requires an additional HTTP request. This could be an issue for a highly interactive user experience. But on the other hand, using a separate request allows you to take advantage of Rails [conditional GET features](https://guides.rubyonrails.org/v3.2/caching_with_rails.html#conditional-get-support)
183+
One downside of moving our dynamic CSS to a separate controller action is that it requires an additional HTTP request. This could be an issue for a highly interactive user experience. But on the other hand, using a separate request allows you to take advantage of Rails [conditional GET features](https://guides.rubyonrails.org/v3.2/caching_with_rails.html#conditional-get-support)
184184

185185
> Conditional GETs are a feature of the HTTP specification that provide a way for web servers to tell browsers that the response to a GET request hasn't changed since the last request and can be safely pulled from the browser cache.
186186
>
@@ -194,6 +194,15 @@ This method will calculate a value for `Etag` or `Last-Modified` response header
194194

195195
In short, dynamic CSS combined with a conditional GET allows you to leverage put Ruby logic behind your stylesheet link tags in a performant manner.
196196

197+
## Which approach is right for you?
198+
199+
There‘s no one right answer here but consider the tradeoffs. Both work well with Hotwire; just like any other element, our style tags and stylesheet link tags can be nested inside a Turbo Frame or can be manipulated with a Turbo Stream if we need some interactivity. With a `<style>` tag, no extra requests to your Rails endpoints are needed to render the page. Separating dynamic css into a controller action can help address bandwidth as response body length as your dynamic styles grow more numerous.
200+
201+
My thought process is usually:
202+
203+
- start with dynamic css straight into HTML within a `<style>`
204+
- move to a controller action when more flexibility is needed or when HTTP caching features are desired
205+
197206
## Recap
198207

199208
Rails provides us with all sorts of [sharp knives](https://rubyonrails.org/doctrine#provide-sharp-knives) especially it comes to dynamic rendering in various formats, like CSS.

0 commit comments

Comments
 (0)