Dynamically Assigning unique IDs to the Body tag of Pages using Rails
In PHP there's a clever trick where, based on the URL of a page, you can automatically assign a unique ID to the body tag of every page on your site. (which i find super helpful in writing CSS).
e.g.
<?php
$url = explode('/',$_SERVER['REQUEST_URI']);
$dir = $url[1] ? $url[1] : 'home';
?>
<body id="<?php echo $dir ?>">
-> source: http://css-tricks.com/snippets/wordpress/id-the-body-based-on-url/
The Result being that,
- a page with a url of "http://domain.tld/blog/home" gets a body with an ID of "blog", and
- a page with a url of "http://domain.tld" gets an ID of "home".
I'd like to 开发者_StackOverflowknow if there's an, (ideally) equally simple and elegant, way to do the same in a Ruby on Rails based website?
Thanks so much for sharing your wisdom, oh great mucky mucks of code!
You could name it by controller and action by adding adding the following in application_controller.rb:
before_filter :create_body_id
def create_body_id
@body_id = "#{params[:controller]}-#{params[:action]}"
end
Then add this in the template: id="<%= @body_id %>"
For the index action in blog_controller you'd get id="blog-index"
精彩评论