【Rails】content_tag를 사용하여 고정된 화면 helper화

6599 단어 RubyRails

content_tag


이렇게 편리한 방법을 알게 되었습니다.
이로써 〃라벨을 생성할 수 있다.
자세한 내용은 아래↓ 참조
http://railsdoc.com/references/content_tag
https://kana-linux.info/rails/rails%E3%81%AEview-helper%E3%81%A7html%E3%82%BF%E3%82%B0%E3%82%92%E5%87%BA%E5%8A%9B%E3%81%99%E3%82%8B

content_helper로 만들기


bootstrap과 함께 사용

flash[:notice], flash[:alert]


users_controller.rb
def create
  @user = User.new(user_params)
  if @user.save
    redirect_to toppage_path, notice: "success"
  else
    render 'new'
  end
end
toppage.html.erb
<% if flash[:notice] %>
  <div class="container">
    <div class="alert alert-success">
      <%= flash[:notice] %>
    </div>
  </div>
<% end %>
<% if flash[:alert] %>
  <div class="container">
    <div class="alert alert-danger">
      <%= flash[:alert] %>
    </div>
  </div>
<% end %>
일반적으로view로 이렇게 쓰는 것이 비교적 많다고 생각한다content_tag그렇지만
helper로 기술하면, ↓
application_helper.rb
  def notice_msg
    if flash[:notice]
      content_tag(:div, class: "container") do
        content_tag(:div, class: "alert alert-success") do
          flash[:notice]
        end
      end
    end
  end
  def alert_msg
    if flash[:alert]
      content_tag(:div, class: "container") do
        content_tag(:div, class: "alert alert-danger") do
          flash[:alert]
        end
      end
    end
  end
toppage.html.erb
<%= notice_msg %>
<%= alert_msg %>
이렇게 하면view 템플릿의 줄 수를 압축할 수 있습니다.

errors.full_messages


이것은 검증 오류 정보를 표시하는 전형적인 유형입니다.
users_controller.rb
def create
  @user = User.new(user_params)
  if @user.save
    redirect_to toppage_path, notice: "success"
  else
    render 'new'
  end
end
new.html.erb

<%= @user.errors.full_messages.each do |msg| %>
  <div class="alert alert-danger">
    <%= msg %>
  </div>
<% end %>
<%= form_with model: @user, local: true do |f| %>
・
・
내가 보기에 이렇게 쓴 것이 비교적 많다.하지만, helper로 기술하기↓
application_helper.rb
  def errors_full_messages(var)
    var.errors.full_messages.each do |msg|
      concat (content_tag(:div, class: "alert alert-danger") do
        msg
      end)
    end
  end
↑()의 사용법은 더럽다
new.html.erb

<% errors_full_messages(@user) %>
<%= form_with model: @user, local: true do |f| %>
・
・
매개변수의 인스턴스 변수를 사용할 수 있습니다.
이런 느낌은view의 줄 수를 압축할 수 있다.
그래서?를 참고하십시오.

감상


다른 자주 사용하는view에서 고정적으로 사용하는 것들은 helper로 템플릿을 만들고 싶습니다.

좋은 웹페이지 즐겨찾기