Search code examples
ruby-on-rails-3google-plus-one

How to add extra attribute to <html> tag for two controllers (Ruby on Rails)


I'm implementing a Google +1 button for some items in my application. Items are showed by two controller actions in different controllers.

Google +1 wants me to modify my

<html>

tag to

<html itemscope itemtype="http://schema.org/ItemPage">

for those pages which show the Items. What would be the best way to handle this? I have thought about two different solutions.

1) Should I create new layout files for these controllers which would have that modified html-tag but should be other vice the same as the default layout. Then I would need to put the main part of the layout file into a partial so that I don't need to duplicate it. This solution sounds a bit too complex.

2) Another solution might be using content_for. Then I would need to define kind of a default content_for which should be used in all the other controllers and override it in these two controllers.

Later I may need to add similar attributes for one other controller too, so the solution should allow me to easily alter the attributes per controller action.


Solution

  • Can you just use a nested layout?

    E.g. something like:

    app/views/layouts/google_plus.html.erb

    <% content_for :html_attrs do %>itemscope itemtype="http://schema.org/ItemPage"<% end %>
    
    <%= render :template => 'layouts/application' %>
    

    app/views/layouts/application.html.erb

    <html <% content_for( :html_attrs ) %>>
    

    And set google_plus as the layout for those controllers.

    (The Google button relies on JavaScript, right? If so, alternatively you could use this technique to embed JavaScript that adds the attrs in those pages.)

    If you want to be able to set the attrs arbitrarily on a per-controller basis, what about just:

    controller

    def show
    
      @html_attrs = 'itemscope itemtype="http://schema.org/ItemPage"'
    
    end
    

    layout

    <html <%= @html_attrs %>>
    

    Obviously you might want to generalize that somehow to apply to several actions.