How do I simplify this component which uses an if statement just to add a single class?

I have the code below that adds a “pt-8” class for any div that is not the first child. Is there a way I can simplify this since I cannot interpolate a string with an uppercase sigil?

  def feature(assigns) do
    if assigns[:first] do
      ~H"""
      <div class="flex gap-x-2">
      </div>
      """
    else
      ~H"""
      <div class="flex pt-8 gap-x-2">
      </div>
      """
    end

You can just use CSS:

class="flex gap-x-2 first:pt-0 pt-8"

Though assuming this is Tailwind you can use space-y-8 which will create even spacing between elements.

Otherwise…

You can do this instead of interpolation:

class={["flex gap-x-2", !@first && "pt-8"]}

…although you can interpolate inside HEEx delimeters: ~H|<%= "#{@foo}" %>|.

Unless I’m missing something, the space-y solution is the simplest, otherwise I’d go with first:pt-0. No need for the @first assign.

6 Likes

Thank you!

1 Like