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"></span>
  <% end %>

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

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.


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


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")

  def domain("") do
    content_tag(:span, "", class: "name name-placeholder")
  def domain(domain) do
    content_tag(:span, domain, class: "name")

Yeah, that’s actually very neat, thanks.