자바스크립트를 허용해주세요.
[ 자바스크립트 활성화 방법 ]
from Mohon Aktifkan Javascript!
 

[Ruby on Rails] 3장. 뷰와 레이아웃

728x90

✅ 1.레이아웃 만들기 

  • 레이아웃(layout): 앱, 전체 공통 틀(Header/Footer/공통 meta 등) 기본 파일은 app/views/layouts/application.html.erb 
  • Rails는 컨트롤별 레이아웃도 자동으로 찾음(없으면 application 사용)
  • yield: 현재 렌더링 되는 뷰(액션의 뷰)를 삽입하는 자리, 기본 yield 하나는 뷰 전체가 들어감
  • content_for / yield(:name): 특정 위치(ex. head, scripts, title)로 뷰에서 내용을 주입할 때 사용
    • 페이지별 CSS/JS, 타이틀 등 주입에 유용함

✅ 2. 기본 application.html.erb 예제

아래 템플릿에는 CSRF, 메타, 기본 스타일/스크립트 로드, 플래시 표시, yield 와 content_for 을 사용하는 예제입니다

  • 라우터와 컨트롤러 생성
rails g controller posts show
# config/routes.rb 에 아래 한 줄 추가(생성기에서 자동으로 안되면)
# get 'posts/show', to: 'posts#show'
  • config/routes.rb 에서
Rails.application.routes.draw do
  get "posts/show", to: "post#show"
  root "posts#show"
   resources :articles
  resources :posts
end
  • 컨트롤러 내용(테스트용) - app/controllers/posts_controller.rb
class PostsController < ApplicationController
  def index
    @posts = Post.all
  end

  def show
    # @post = Post.find(params[:id])
    @post = Post.new(title: "테스트", body: "본문 내용, 한글 표시 확인")
    @post_title = "테스트 글"
    @post_body = "본문 내용, 한글 표시 확인"
  end
end
  • 레이아웃 파일 만들기 / 수정 - app/views/layouts/application.html.erb 
<!DOCTYPE html>
<html lang="ko">
  <head>
    <meta charset="utf-8" />
    <%= csrf_meta_tags %> <%= csp_meta_tag %>

    <title><%= content_for?(:title) ? yield(:title) : "MyApp" %></title>

    <%= stylesheet_link_tag "application", "data-turbo-track": "reload" %> <%=
    yield :head %>
  </head>
  <body>
    <header>
      <%= render 'shared/header' if lookup_context.exists?('shared/_header') %>
    </header>

    <main>
      <% if notice %>
      <p class="notice"><%= notice %></p>
      <% end %> <% if alert %>
      <p class="alert"><%= alert %></p>
      <% end %> <%= yield %>
    </main>

    <footer>&copy; <%= Time.current.year %> MyApp</footer>

    <%= javascript_include_tag "application", "data-turbo-track": "reload" %>
    <%= yield :scripts %>
  </body>
</html>

 


 ✅ 뷰에서 content_for 사용

뷰(app/views/posts/show.html.erb) 에서 타잍틀과 페이지 전용 스크립트/스타일을 넣을 수 있습니다.

<% content_for :title do %> <%= @post_title %> | My_Blog <% end %> <%
content_for:head do %>
<style>
  /* 페이지 전용 스타일 */
</style>
<% end %>

<article>
  <h1><%= @post_title %></h1>
  <p><%= @post_body%></p>
</article>

<% content_for :scripts do %>
<script>
  console.log("Post show ready");
</script>
<% end %>
  • (선택) partial 테스트 - app/views/shared/_header.html.erb
<nav>
  <%= link_to "Home", root_path %> |
  <%= link_to "Posts", posts_show_path %>
</nav>
  • 서버 실행 전 마이그레이트 생성 - 오류 발생 시 (거의 100%) 
rails generate migration AddBodyToPosts body:text
rails db:migrate
bin/rails server 
# or rails s

 

  • 확인 포인트 
    • 브라우저 탭 타이틀에 테스트 | MyBlog 나오는지?
    • 개발자 도구 콘솔에 Post show ready 로그 찍히는지 확인(스크립트가 yield: scripts 위치에 들어왔는지?)
    • header partial이 보이는지 footer 연도 표시 보이는지 
    • 레이아웃 오버라이드 테스트 (컨트롤러별 레이아웃)
      • app/views/layouts/admin.html.erb 파일 생성후 Admin:DashboardController에서
class Admin::DashboardController < ApplicationController
  layout "admin"
  def index; end
end

 

이러면 해당 컨트롤러는 admin 레이아웃을 사용


 

 

GitHub - Koras02/rails-bloging: https://thinky.tistory.com/category/Back-End/Ruby

https://thinky.tistory.com/category/Back-End/Ruby. Contribute to Koras02/rails-bloging development by creating an account on GitHub.

github.com

 

728x90
LIST