Haml: Prevent whitespace from being stripped in production

Updated . Posted . Visible to the public.

Disclaimer

This is not an issue in newer versions of HAML (starting with 5.0.0), as the ugly-option was removed Show archive.org snapshot so that in development everything is rendered ugly, too.

Problem

When HTML is rendered from HAML in production or staging environment, whitespace is removed to reduce the download size of the resulting pages. Therefore it might happen that whitespace you see in development is missing in production or staging.

Here is an example of two inlined bootstrap buttons in a table:

%td
  = link_to edit_admin_user_path(membership.user_id), class: 'btn' do
    Edit
  = link_to admin_membership_path(membership), method: :delete, class: 'btn' do
    Delete

In development you will see a small space between the buttons. In staging however, there is no space between the buttons.

Solution

To fix this, you could simply add an empty line after "Edit". Unfortunately this doesn't stop another developer from removing the empty line.
Instead it would be a good idea to create a helper method in application_helper.rb to make the intended whitespace more explicit:

def space
  # prevent haml whitespace being stripped in staging and production
  # which would lead to elements being stuck together.
  # As in development whitespace is not stripped, it looks good in
  # development even without this helper.
  ' '
end

Then you can add the space to your HAML file:

%td
  = link_to edit_admin_user_path(membership.user_id), class: 'btn' do
    Edit
  = space
  = link_to admin_membership_path(membership), method: :delete, class: 'btn' do
    Delete
Daniel Straßner
Last edit
Daniel Straßner
Keywords
staging
License
Source code in this card is licensed under the MIT License.
Posted by Daniel Straßner to makandra dev (2017-03-14 14:51)