Hotwire Discussion

Displaying different templates depending on containing page

I’m building a small checklist app. Todo items are displayed both on checklist#edit and checklist#show - right now streamed to both pages - but I’d like to use slightly different templates on the different pages. Since both pages are receiving streams from todos/new I’m not sure how to include the page-wide context. Is that something that’s even possible, or should I just use some javascript to hide the delete after-the-fact?

controllers/todos_controller.rb

def create
  @todo = @checklist.todos.new(todo_params)

  respond_to do |format|
    if @todo.save
      format.turbo_stream
      format.html { redirect_to edit_checklist_path(@checklist) }
    else
      format.html { head :unprocessable_entity }
    end
  end
end

models/todo.rb

class Todo < ApplicationRecord
  belongs_to :checklist
  validates :description, presence: true

  broadcasts_to :checklist
end

views/…/_todo.html.erb

<div class="todo-item" id="<%= dom_id todo %>">
  <div class="form-check">
    <input class="form-check-input" type="checkbox" value="" id="checkbox-<%= dom_id todo %>" disabled />
    <label class="form-check-label" for="checkbox-<%= dom_id todo %>"><%= todo.description %></label>

    <!-- I'd like for the delete item to be shown only on `checklist#edit` and not `checklist#show` -->
    <span class="float-right">
      <%= link_to todo_path(todo), method: :delete do %>
        <i class="fas fa-times"></i>
      <% end %>

    </span>
  </div>
</div>

I think your suggestion is correct, simply hiding the button after it was pressed seems the best solution.

1 Like