Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
761 views
in Technique[技术] by (71.8m points)

elixir - Use Integer.is_even(count) in a template

I customize the phx.gen.html template to use TailwindCSS. In the :show template I use this code:

<%= for {{k, _}, counter} <- Enum.with_index(schema.attrs) do %>
  <% bg_color = if Integer.is_even(counter), do: "bg-gray-50", else: "bg-white" %>
  <div class="<%= bg_color %>">
    [...]
  </div>
<% end %>

Running the generator results in this error message:

** (CompileError) ./priv/templates/tailwind.gen.html/show.html.eex:10: 
you must require Integer before invoking the macro Integer.is_even/1
    (elixir 1.11.2) expanding macro: Kernel.if/2
    ./priv/templates/tailwind.gen.html/show.html.eex:10: (file)

The Integer.is_even(counter) is the problem.

  • How can I require Integer here?
  • Is there a better/easier/cleaner way to iterate the value of bg_color between "bg-gray-50" and "bg-white"?

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I'm not super familiar with tailwindcss, but this can typically be done purely through CSS.

It looks to me like tailwindcss does support an "even-child" variant.

So I would imagine after a small tweak to your tailwind config you could just give all your divs the same class (I believe CSS child indices start at 1, so I'm flipping what's "even"):

<%= for {k, _} <- schema.attrs do %>
  <div class="bg-gray-50 even:bg-white">
    [...]
  </div>
<% end %>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...