Class: Middleman::TemplateContext

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
Contracts
Defined in:
middleman-core/lib/middleman-core/template_context.rb

Overview

The TemplateContext Class

A clean context, separate from Application, in which templates can be executed. All helper methods and values available in a template, but be accessible here. Also implements two helpers: wrap_layout & render (used by padrino's partial method). A new context is created for each render of a path, but that context is shared through the request, passed from template, to layouts and partials.

Constant Summary

Constants included from Contracts

Contracts::ImmutableSetOf, Contracts::ImmutableSortedSetOf, Contracts::OldResourceList, Contracts::PATH_MATCHER, Contracts::ResourceList, Contracts::VectorOf

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Contracts

#Contract

Constructor Details

#initialize(app, locs = {}, options_hash = ::Middleman::EMPTY_HASH) ⇒ TemplateContext

Initialize a context with the current app and predefined locals and options hashes.

Parameters:


43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'middleman-core/lib/middleman-core/template_context.rb', line 43

def initialize(app, locs = {}, options_hash = ::Middleman::EMPTY_HASH)
  @app = app
  @opts = options_hash

  @vertices = ::Hamster::Set.empty
  @data = DataProxy.new(self)

  @locs = if @app.config[:track_data_access]
            @data.take_ownership_of_proxies(locs)
          else
            locs
          end
end

Instance Attribute Details

#appMiddleman::Application (readonly)

Allow templates to directly access the current app instance.


24
25
26
# File 'middleman-core/lib/middleman-core/template_context.rb', line 24

def app
  @app
end

#current_engineObject

Required for Padrino's rendering


27
28
29
# File 'middleman-core/lib/middleman-core/template_context.rb', line 27

def current_engine
  @current_engine
end

#dataObject (readonly)

Points to the data proxy, which records data accesses


30
31
32
# File 'middleman-core/lib/middleman-core/template_context.rb', line 30

def data
  @data
end

#verticesObject

Returns the value of attribute vertices


33
34
35
# File 'middleman-core/lib/middleman-core/template_context.rb', line 33

def vertices
  @vertices
end

Instance Method Details

#AnyString

Sinatra/Padrino compatible render method signature referenced by some view helpers. Especially partials.

Parameters:

  • name (String, Symbol)

    The partial to render.

  • options (Hash)
  • block (Proc)

    A block will be evaluated to return internal contents.

Returns:


123
# File 'middleman-core/lib/middleman-core/template_context.rb', line 123

Contract Any, Or[Symbol, String], Hash, Hash, Maybe[Proc] => String

#current_pathObject


194
195
196
# File 'middleman-core/lib/middleman-core/template_context.rb', line 194

def current_path
  @locs[:current_path]
end

#current_resourceMiddleman::Sitemap::Resource Also known as: current_page

Get the resource object for the current path


200
201
202
203
204
# File 'middleman-core/lib/middleman-core/template_context.rb', line 200

def current_resource
  return nil unless current_path

  sitemap.by_destination_path(current_path)
end

#locate_partial(partial_path, try_static = true) ⇒ Object


154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
# File 'middleman-core/lib/middleman-core/template_context.rb', line 154

def locate_partial(partial_path, try_static = true)
  partial_file = nil
  lookup_stack = []
  non_root     = partial_path.to_s.sub(/^\//, '')
  non_root_no_underscore = non_root.sub(/^_/, '').sub(/\/_/, '/')

  if current_resource
    resource = current_resource
    current_dir  = resource.file_descriptor[:relative_path].dirname
    relative_dir = current_dir + Pathname(non_root)
    relative_dir_no_underscore = current_dir + Pathname(non_root_no_underscore)

    if relative_dir
      lookup_stack.push [relative_dir.to_s,
                         { preferred_engine: resource.file_descriptor[:relative_path]
                                                     .extname[1..-1].to_sym }]
    end
  end

  lookup_stack.push [non_root]

  lookup_stack.push [non_root,
                     { try_static: try_static }]

  if relative_dir_no_underscore
    lookup_stack.push [relative_dir_no_underscore.to_s,
                       { try_static: try_static }]
  end

  lookup_stack.push [non_root_no_underscore,
                     { try_static: try_static }]

  lookup_stack.each do |args|
    partial_file = ::Middleman::TemplateRenderer.resolve_template(@app, *args)
    break if partial_file
  end

  partial_file
end

#render(_, name, options_hash, locals, &block) ⇒ Object


124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
# File 'middleman-core/lib/middleman-core/template_context.rb', line 124

def render(_, name, options_hash, locals, &block)
  name = name.to_s

  partial_file = locate_partial(name, false) || locate_partial(name, true)

  raise ::Middleman::TemplateRenderer::TemplateNotFound, "Could not locate partial: #{name}" unless partial_file

  source_path = sitemap.file_to_path(partial_file)
  r = sitemap.by_path(source_path)

  @vertices <<= ::Middleman::Dependencies::FileVertex.from_source_file(@app, partial_file)

  result = if (r && !r.template?) || (Tilt[partial_file[:full_path]].nil? && partial_file[:full_path].exist?)
             partial_file.read
           else
             opts = options_hash.dup
             locs = locals

             render_file(partial_file, locs, opts, &block)
           end

  result
end

#restore_buffer(buf_was)

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

Restore a previously saved buffer.

Parameters:


73
74
75
# File 'middleman-core/lib/middleman-core/template_context.rb', line 73

def restore_buffer(buf_was)
  @_out_buf = buf_was
end

#save_bufferString

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Return the current buffer to the caller and clear the value internally. Used when moving between templates when rendering layouts or partials.

Returns:

  • (String)

    The old buffer.


62
63
64
65
66
# File 'middleman-core/lib/middleman-core/template_context.rb', line 62

def save_buffer
  buf_was = @_out_buf
  @_out_buf = ''
  buf_was
end

#StringString

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Locate a partial relative to the current path or the source dir, given a partial's path.

Parameters:

Returns:


153
# File 'middleman-core/lib/middleman-core/template_context.rb', line 153

Contract String, Maybe[Bool] => Maybe[IsA['Middleman::SourceFile']

#wrap_layout(layout_name, &block)

This method returns an undefined value.

Allow layouts to be wrapped in the contents of other layouts.

Parameters:

  • layout_name (String, Symbol)

81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
# File 'middleman-core/lib/middleman-core/template_context.rb', line 81

def wrap_layout(layout_name, &block)
  # Save current buffer for later
  buf_was = save_buffer

  # Find a layout for this file
  layout_file = ::Middleman::TemplateRenderer.locate_layout(@app, layout_name, current_engine)

  # Get the layout engine
  extension = File.extname(layout_file[:relative_path])
  engine = extension[1..-1].to_sym

  # Store last engine for later (could be inside nested renders)
  self.current_engine = engine
  engine_was = current_engine

  # By default, no content is captured
  content = ''

  # Attempt to capture HTML from block
  begin
    content = capture_html(&block) if block_given?
  ensure
    # Reset stored buffer, regardless of success
    restore_buffer(buf_was)
  end

  @vertices <<= ::Middleman::Dependencies::FileVertex.from_source_file(@app, layout_file)

  # Render the layout, with the contents of the block inside.
  concat_safe_content render_file(layout_file, @locs, @opts) { content }
ensure
  # Reset engine back to template's value, regardless of success
  self.current_engine = engine_was
end