How to Use stylesheet_link_tag in Ruby on Rails
Use
stylesheet_link_tag in Ruby on Rails views to include CSS files by passing the stylesheet names as arguments. It generates HTML <link> tags that load your stylesheets automatically.Syntax
The stylesheet_link_tag helper generates HTML <link> tags to include CSS files in your Rails views. You pass one or more stylesheet names as strings without the .css extension. You can also add options like media or integrity.
ruby
stylesheet_link_tag(name, *names, **options)
Example
This example shows how to include a single stylesheet and multiple stylesheets in a Rails view using stylesheet_link_tag. It also demonstrates adding a media attribute.
erb
<!DOCTYPE html> <html lang="en"> <head> <title>Example</title> <%= stylesheet_link_tag "application", media: "all" %> <%= stylesheet_link_tag "custom", "theme", media: "screen" %> </head> <body> <h1>Hello, Rails!</h1> </body> </html>
Output
<!DOCTYPE html>
<html lang="en">
<head>
<title>Example</title>
<link rel="stylesheet" media="all" href="/assets/application.css" />
<link rel="stylesheet" media="screen" href="/assets/custom.css" />
<link rel="stylesheet" media="screen" href="/assets/theme.css" />
</head>
<body>
<h1>Hello, Rails!</h1>
</body>
</html>
Common Pitfalls
- Forgetting to omit the
.cssextension causes the helper to look for a file with.css.css, which breaks the link. - Using incorrect stylesheet names that don’t exist in the assets folder will result in missing CSS.
- Not precompiling assets in production can cause stylesheets not to load.
- Passing options incorrectly, like using a string instead of a symbol for keys, can cause errors.
erb
<!-- Wrong: includes extension --> <%= stylesheet_link_tag "application.css" %> <!-- Right: omit extension --> <%= stylesheet_link_tag "application" %>
Quick Reference
Use stylesheet_link_tag to include CSS files in your Rails views. Pass stylesheet names without extensions. Add options like media or integrity as needed. It outputs HTML <link> tags for stylesheets.
| Usage | Description |
|---|---|
| stylesheet_link_tag "application" | Includes application.css stylesheet |
| stylesheet_link_tag "custom", "theme" | Includes multiple stylesheets |
| stylesheet_link_tag "print", media: "print" | Includes stylesheet for print media |
| stylesheet_link_tag "application", integrity: "sha384-..." | Adds Subresource Integrity attribute |
Key Takeaways
Use stylesheet_link_tag to include CSS files by passing names without the .css extension.
It generates HTML tags that load stylesheets in your Rails views.
Add options like media or integrity to customize how stylesheets load.
Avoid including the .css extension to prevent broken links.
Ensure assets are precompiled in production for stylesheets to load correctly.