 getTemplateInstance = (view) ->
-  while view and not view.template
+  while view and not view._templateInstance
     view = view.originalParentView or view.parentView
 
-  # Body view has template field, but not templateInstance, so we have ? at the end.
-  view?.templateInstance?()
+  view?._templateInstance
 
 # More or less the same as aldeed:template-extension's template.get('component') just specialized.
 # It allows us to not have a dependency on template-extension package and that we can work with Iron

    throw new Error "Expected DOM element." unless domElement.nodeType is Node.ELEMENT_NODE

    templateInstanceToComponent =>
      Blaze.getView(domElement)?.templateInstance()

  mixins: ->
    []

  # Caller-level component. In most cases the same as @, but in event handlers
  # it returns the component at the place where event originated (target component).
  currentComponent: ->
    # Template.instance() registers a dependency on the template instance data context,
    # but we do not need that. We just need a template instance to resolve a component.
    Tracker.nonreactive =>
      templateInstanceToComponent Template.instance

  firstNode: ->
    view = @_componentInternals.templateInstance.view
    if view._domrange and not view.isDestroyed
      view._domrange.firstNode()
    else
      null

  lastNode: ->
    view = @_componentInternals.templateInstance.view
    if view._domrange and not view.isDestroyed
      view._domrange.lastNode()
    else
      null

# We copy utility methods ($, findAll, autorun, subscribe, etc.) from the template instance prototype.
for methodName, method of Blaze.TemplateInstance::
