ruby-on-railsruby-on-rails-3whitespacerendercontent-for

Extra whitespace around content_for value


I need to give my body tag a page-specific id to better target css selectors.

To this end I have set up the following in my application.erb layout:

<body id="<%= content_for :page_id %>">

Inside a page's view I can then do this:

<% content_for :page_id do %>
  <%='some-page-id'%>
<% end %>

The problem is that I am getting extra whitespace returned around the returned value resulting in the rendered body tag looking like this:

<body id="    some-page-id " >

This prevents the id from working. I have a workaround in place where I do this:

<% body_id = content_for :page_id %>
<body id="<%= body_id.strip %>">

But is there a way to fix this so that content_for returns its value without extra whitespace? What is causing this extra whitespace to be returned?


Solution

  • What is causing this extra whitespace to be returned?

    The space

    <% content_for :page_id do %>
      <%='some-page-id'%>
    <% end %>
    

    You could try this:

    <%- content_for :page_id do -%>
      <%='some-page-id'%>
    <%- end -%>