dry-view

v0.8
  1. Introduction
  2. Configuration
  3. Injecting dependencies
  4. Exposures
  5. Templates
  6. Parts
  7. Scopes
  8. Context
  9. Testing

TOC

  1. Concepts
  2. Example

Introduction

Development of dry-view has ceased. Please switch to hanami-view for a compatible replacement.

dry-view is a complete, standalone view rendering system that gives you everything you need to write well-factored view code.

Use dry-view if:

Concepts

dry-view divides the responsibility of view rendering across several different components:

Example

Configure your view, accept some dependencies, and define an exposure:

require "dry/view"

class ArticleView < Dry::View
  config.paths = [File.join(__dir__, "templates")]
  config.part_namespace = Parts
  config.layout = "application"
  config.template = "articles/show"

  attr_reader :article_repo

  def initialize(article_repo:)
    @article_repo = article_repo
  end

  expose :article do |slug:|
    article_repo.by_slug(slug)
  end
end

Write a layout (templates/layouts/application.html.erb):

<html>
  <body>
    <%= yield %>
  </body>
</html>

And a template (templates/articles/show.html.erb):

<h1><%= article.title %></h1>
<p><%= article.byline_text %></p>

Define a part to provide view-specific behavior around the exposed article value:

module Parts
  class Article < Dry::View::Part
    def byline_text
      authors.map(&:name).join(", ")
    end
  end
end

Then #call your view to render the output:

view = ArticleView.new
view.call(slug: "cheeseburger-backpack").to_s
# => "<html><body><h1>Cheeseburger Backpack</h1><p>Rebecca Sugar, Ian Jones-Quartey</p></body></html>

Dry::View::#call expects keyword arguments for input data. These arguments are handled by your exposures, which prepare view parts that are passed to your template for rendering.