Class: Shaven::Presenter
- Includes:
- Helpers::HTML
- Defined in:
- lib/shaven/presenter.rb
Overview
Presenters are placeholder for all logic which is going to fill in your html templates. Remember that presenters shouldn’t contain any raw HTML code, you can generate it using html helpers (see Shaven::Helpers::HTML
for details).
Simple example
class DummyPreseneter < Shaven::Presenter
def title
"Hello world!"
end
end
presenter = DummyPreseneter.feed("<!DOCTYPE html><html><body><h1 rb="title">Example...</h1></body><html>")
presenter.to_html # => ...
DOM Manipulation
If your presenter method has one argument, then related DOM node will be passed to it while transformation process. You can use it to change its attributes or content, replace it with other node or text, remove it, etc.
class DummyPresenter < Shaven::Presenter
def title(node)
node.update!(:id => "title") { "Hello world!" }
end
end
HTML helpers
Shaven’s presenters provides set of helpers to generate extra html nodes. Take a look at example:
class DummyPresenter < Shaven::Presenter
def login_link
a(:href => login_path) { "Login to your account!" }
end
def title
tag(:h1, :id => "title") { "Hello world!" }
end
end
Instance Attribute Summary collapse
-
#scope ⇒ Object
readonly
Returns the value of attribute scope.
Class Method Summary collapse
Instance Method Summary collapse
- #compiled? ⇒ Boolean
-
#initialize(document) ⇒ Presenter
constructor
A new instance of Presenter.
- #render(context = {}) ⇒ Object (also: #to_html)
Methods included from Helpers::HTML
Constructor Details
Instance Attribute Details
#scope ⇒ Object (readonly)
Returns the value of attribute scope.
63 64 65 |
# File 'lib/shaven/presenter.rb', line 63 def scope @scope end |
Class Method Details
.feed(tpl) ⇒ Object
54 55 56 |
# File 'lib/shaven/presenter.rb', line 54 def feed(tpl) new(Document.new(tpl)) end |
.render(tpl, context = {}) ⇒ Object
58 59 60 |
# File 'lib/shaven/presenter.rb', line 58 def render(tpl, context={}) feed(tpl).render(context) end |
Instance Method Details
#compiled? ⇒ Boolean
81 82 83 |
# File 'lib/shaven/presenter.rb', line 81 def compiled? !!@compiled end |
#render(context = {}) ⇒ Object Also known as: to_html
70 71 72 73 74 75 76 77 78 |
# File 'lib/shaven/presenter.rb', line 70 def render(context={}) unless compiled? @scope.unshift(context.stringify_keys) unless context.empty? Transformer.apply!(@scope.with(@document.root)) @compiled = true end @document.to_html end |