Class: Roger::TemplateContext

Inherits:
Object
  • Object
show all
Defined in:
lib/roger/template.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(template, env = {}) ⇒ TemplateContext

Returns a new instance of TemplateContext.



149
150
151
152
# File 'lib/roger/template.rb', line 149

def initialize(template, env={})
  @_content_for_blocks = {}
  @_template, @_env = template, env
end

Instance Attribute Details

#_content_for_blocksObject

Returns the value of attribute _content_for_blocks.



147
148
149
# File 'lib/roger/template.rb', line 147

def _content_for_blocks
  @_content_for_blocks
end

Instance Method Details

#capture(&block) ⇒ Object



185
186
187
188
189
190
191
192
193
# File 'lib/roger/template.rb', line 185

def capture(&block)
  raise ArgumentError, "content_for works only with ERB Templates" if !self.template.template.kind_of?(Tilt::ERBTemplate)
  eval "@_erbout_tmp = _erbout", block.binding
  eval "_erbout = \"\"", block.binding
  t = Tilt::ERBTemplate.new(){ "<%= yield %>" }
  t.render(&block)      
ensure
  eval "_erbout = @_erbout_tmp", block.binding
end

#content_for(block_name, &block) ⇒ Object

Capture content in blocks in the template for later use in the layout. Currently only works in ERB templates. Use like this in the template:

“‘

<% content_for :name %> bla bla <% end %>

“‘

Place it like this in the layout:

“‘

<%= yield :name %>

“‘



181
182
183
# File 'lib/roger/template.rb', line 181

def content_for(block_name, &block)
  @_content_for_blocks[block_name] = capture(&block)
end

#documentObject

Access to the front-matter of the document (if any)



160
161
162
# File 'lib/roger/template.rb', line 160

def document
  @_data ||= OpenStruct.new(self.template.data)
end

#envObject

The current environment variables.



165
166
167
# File 'lib/roger/template.rb', line 165

def env
  @_env
end

#partial(name, options = {}, &block) ⇒ Object



195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
# File 'lib/roger/template.rb', line 195

def partial(name, options = {}, &block)
  if template_path = self.template.find_template(name, :partials_path)
    partial_template = Tilt.new(template_path.to_s)
    if block_given?
      block_content = capture(&block)
    else
      block_content = ""
    end
    out = partial_template.render(self, options[:locals] || {}){ block_content }

    if block_given?
      eval "_erbout.concat(#{out.dump})", block.binding
    else
      out
    end
  else
    raise ArgumentError, "No such partial #{name}, referenced from #{self.template.source_path}"
  end
end

#templateObject

The current Roger::Template in use



155
156
157
# File 'lib/roger/template.rb', line 155

def template
  @_template
end