Project structure // UI components

In addition to the libraries like Surface, Temple, and LiveComponents, you can create your own components using the plain old render/3 function.

From inside your main template, you can render another template:

web/controllers/fruit_controller.ex:

defmodule Web.FruitController do
  use Web, :controller

  def index(conn, _params) do
    render(conn, fruit: GroceryStore.all_fruit())
  end
end

web/templates/fruit/index.html.slim (slime):

h1 Fruit

= render Web.TableView, "table.html", id: "all-fruit", columns: [{"Name", :name}, [{"Rating", :rating}], data: @fruit

web/views/table_view.ex:

defmodule Web.TableView do
  use Web, :view
end

web/templates/table/table.html.slim:

table id=@id
  thead
    tr
      = for {title, _key} <- @columns do
        th= title

  tbody
    = for datum <- @data do
      tr do
        = for {_title, key} <- @columns do
          td= datum[key]

assets/css/app.sass:

@import "components"

table#all-fruit
  @include data-table($padding: 1rem)

assets/css/components.sass:

@mixin data-table($padding: 0.5rem)
  td, th
    font-size: 14px
    padding: $padding

  th
    background-color: blue

So now you’ve got a reusable, parameterized table component to render HTML, and a reusable, parameterized Sass function to render CSS. That should give you a nice combination of reuse and customizability.

3 Likes