Is there a way to trim whitespace in EEx files?

Whitespace can be a real pain in the neck in HTML, consider a .html.eex file like this one:

  <%= if www_prefix? do %>
    <span class="prefix">www.</span>
  <% end %>

  <%= if String.length(@domain_name) > 0 do %>
    <span class="name"><%= @domain_name %></span>
  <% else %>
    <span class="name name-placeholder">example.net</span>
  <% end %>

This will, when the prefix condition is true, render domain names like www. example.net with an (unwanted) space showing up between www. and example.net.

There are a bunch of nasty ways to get around this problem (CSS tricks, putting everything on one line with no spaces, etc.), but I haven’t been able to find a clean one, where I can format my .eex file properly, but avoid having whitespace in the output.

Twig has a mechanism for that, basically {{- value -}} strips whitespace before and after the tag, where {{ value }} does not. Is there a way to accomplish the same with EEx? It does have a trim parameter when calling it directly, but I don’t think that strips whitespace between HTML tags, only from the start and beginning of the entire template.

I know this does not directly answer your question, but I would probably approach this like so.

foo.html.eex

<%= prefix() %><%= domain(@domain) %>

foo_view.ex

defmodule MyApp.FooView do
  use MyAppWeb, :view

  def prefix() do
    # Add some logic here to decide whether or not to show the prefix.
    content_tag(:span, "www.", class: "prefix")
  end

  def domain("") do
    content_tag(:span, "example.net", class: "name name-placeholder")
  end
  def domain(domain) do
    content_tag(:span, domain, class: "name")
  end
end
5 Likes

Yeah, that’s actually very neat, thanks.