{{/*
  Args: .path .page

  Looks for the page specified by .path, starting from .page, moving up the
  .Parent relation if necessary. If .path isn't explicitly absolute or relative,
  "_includes/" is prepended to it.

  */ -}}

{{ $path := .path -}}
{{ if not (or
  (strings.HasPrefix $path "/" )
  (strings.HasPrefix $path "."))
-}}
  {{ $path = printf "_includes/%s" $path -}}
{{ end -}}

{{ $result := partial "func/_find-include.html" (dict "path" $path "page" .page) -}}
{{ return $result -}}

{{ define "partials/func/_find-include.html" -}}
  {{ $result := "" -}}
  {{ $page_to_include := .page.GetPage .path -}}

  {{ with $page_to_include -}}
    {{ $result = . }}
  {{ else -}}
    {{ $parent := .page.Parent -}}
    {{ if $parent -}}
      {{ $result = partial "func/_find-include.html" (dict "path" .path "page" $parent) -}}
    {{end -}}
  {{ end -}}

  {{ return $result -}}
{{ end -}}
