Phlex 컴포넌트의 렌더링 과정은 다음과 같은 주요 단계와 기능을 포함합니다.
1. view_template 메서드
-
모든 Phlex 컴포넌트는
view_template메서드를 가지며, 이 메서드에서 컴포넌트의 HTML 렌더링 로직을 구현합니다. -
예시:
ruby class Components::Card < Components::Base def view_template div do h1 { "Hello, World!" } end end end
2. Rails와의 통합 (render_in)
-
Rails 뷰에서
<%= render Components::Card.new %>와 같이 컴포넌트를 렌더링하면, Rails는 해당 인스턴스의#render_in메서드를 호출합니다. -
이 과정은 ViewComponent와 유사하며, Phlex는 최종적으로
#view_template을 호출하기 전에 추가적인 단계를 거칩니다.
3. 렌더링 훅 (Rendering Hooks)
Phlex는 컴포넌트 렌더링 전후 또는 주변에서 특정 로직을 실행할 수 있는 유용한 훅을 제공합니다.
before_template/after_template:view_template실행 전후에 호출됩니다.- 주로 디버깅, 로깅, 계측(instrumentation) 등에 활용됩니다.
- 예시: 개발 환경에서 컴포넌트 HTML 전후에 주석을 추가하여 어떤 컴포넌트가 HTML을 생성했는지 쉽게 파악할 수 있습니다.
ruby class Components::Base < Phlex::HTML if Rails.env.development? def before_template comment { "Before #{self.class.name}" } super end def after_template comment { "After #{self.class.name}" } super end end end
around_template:view_template메서드 주변에서 호출되며, 레이아웃 컴포넌트를 구현하는 데 매우 유용합니다.super를 호출하여 상위 클래스의around_template훅을 실행하고,yield블록을 통해view_template의 내용을 렌더링합니다.- 예시:
Components::Card에서view_template내용을div(class: "card")로 감싸는 레이아웃 구현.ruby class Components::Card < Components::Base def around_template super do div(class: "card") do yield # `view_template` 내용을 렌더링 end end end # ... end
4. 동적인 콘텐츠와 재사용성
-
Phlex의
render메서드는 블록, 프로시저, 메서드 등 다양한 형태의 Phlex 콘텐츠를 렌더링할 수 있습니다. -
컴포넌트 메서드를 활용하여 동적인 제목이나 부제목을 제공하고, 이 메서드들이 일반 문자열이 아닌 Phlex 마크업을 반환하도록 하여 더욱 풍부한 HTML을 생성할 수 있습니다.
-
예시:
Components::TitleCard에서title및subtitle메서드를 정의하고,around_template내에서 이들을 호출하여 동적인 제목 영역을 구현합니다.title메서드가a태그를 포함한 Phlex 마크업을 반환하도록 하여 사용자 프로필 링크를 생성하는 등 유연한 활용이 가능합니다.ruby class Components::TitleCard < Components::Card def title = nil def subtitle = nil def around_template(&block) super do h1 { title } h2 &::subtitle render &block # 블록으로 전달된 콘텐츠 렌더링 end end endruby class Components::ContactCard < Components::TitleCard # ... def title a(href: user_path(@user)) { @user.name } # Phlex 마크업 반환 end # ... end이러한 메커니즘은 컴포넌트의 재사용성과 유연성을 극대화하여 복잡한 UI를 효율적으로 구축할 수 있게 합니다.