Open hungle00 opened 1 year ago
dom_id
The dom_id helper takes a string or any object as an argument that can be converted to a dom_id. And it helps us convert an object into a unique id like this:
post = Post.find(10) dom_id(post) # => "post_10" dom_id(post, new_comment) # => "new_comment_post_10"
dom_id helper is introduced a long time and is become more valuable when working with Hotwire concept like Turbo frame or Turbo stream.
Turbo Frames and the dom_id helper
Because turbo_frame_tag uses the dom_id helper under the hood, so when we write
turbo_frame_tag
post = Post.find(1) turbo_frame_tag(post)
It will return
<turbo-frame id="post_1"></turbo_frame>
One of the most common use cases of Turbo Frame is in-line editing. For example, inline editing comment
<%= turbo_frame_tag comment do %> <div> <%= comment.body %> <%= link_to "Edit", edit_comment_path(comment) %> </div> <% end %>
<%= turbo_frame_tag @comment do %> <%= form_with(model: @comment) do |form| %> <% end %> <% end %>
class_names
class_names helper is supported from Rails 6.1, make easier to conditionally apply class names in views.
<%= tag.div class: class_names("display-none my-2", "display-flex": current_user == @post.author) do %> <%= link_to "Edit", edit_post_path(@post), class: "btn btn--primary" %> <% end %>
<%= tag.div class: ["display-none my-2", "display-flex": current_user == @post.author ] do %> <%= link_to "Edit", edit_post_path(@post), class: "btn btn--primary" %> <% end %>
<%= tag.span class: ["p-2 radius-2", "bg-indigo-2": current_user.admin?, "bg-indigo-4": @post.author?] do %> <%= @post.category %> <% end %>
1. DOM id convention with
dom_id
The
dom_id
helper takes a string or any object as an argument that can be converted to a dom_id. And it helps us convert an object into a unique id like this:dom_id
helper is introduced a long time and is become more valuable when working with Hotwire concept like Turbo frame or Turbo stream.Turbo Frames and the dom_id helper
Because
turbo_frame_tag
uses thedom_id
helper under the hood, so when we writeIt will return
One of the most common use cases of Turbo Frame is in-line editing. For example, inline editing comment
2. Conditionally class name with
class_names
class_names
helper is supported from Rails 6.1, make easier to conditionally apply class names in views.class_names
helper methodclass_names
, so we can write like this: