Files
hinode/layouts/shortcodes/link.html
2024-05-19 13:28:21 +05:00

96 lines
3.1 KiB
HTML

<!--
Copyright © 2024 The Hinode Team / Mark Dumay. All rights reserved.
Use of this source code is governed by The MIT License (MIT) that can be found in the LICENSE file.
Visit gethinode.com/license for more details.
-->
{{ $error := false -}}
<!-- Validate arguments -->
{{ if partial "utilities/IsInvalidArgs.html" (dict "structure" "link" "args" .Params "group" "shortcode") }}
{{ errorf "Invalid arguments: %s" .Position -}}
{{ $error = true }}
{{ end }}
<!-- Initialize arguments -->
{{ $href := "" }}
{{ $name := "" }}
{{ $url := "" }}
{{ $class := "" }}
{{ $case := true }}
{{ $external := false }}
{{ $cue := site.Params.main.externalLinks.cue }}
{{ $tab := site.Params.main.externalLinks.tab }}
{{ $text := trim .Inner " \r\n" | .Page.RenderString | safeHTML }}
{{- $anchor := "" -}}
{{ if .IsNamedParams }}
{{- $href = .Get "href" | default "" -}}
{{- $name = .Get "name" | default "" -}}
{{- $url = .Get "url" | default "" -}}
{{- $cue = .Get "cue" | default site.Params.main.externalLinks.cue -}}
{{- $tab = .Get "tab" | default site.Params.main.externalLinks.tab -}}
{{- $case = .Get "case" | default true -}}
{{- $external = .Get "external" | default false -}}
{{- $class = .Get "class" | default "" -}}
{{ else }}
{{ $href = .Get 0 }}
{{ end }}
{{- $href = or (or $href $name) $url -}}
{{ if not $href }}
{{ errorf "Expected param 'href': %s" .Position -}}
{{ $error = true -}}
{{ end }}
{{- if hasPrefix $href "http" -}}
{{- if $external -}}
{{ $url = $href }}
{{- else -}}
{{ $url = strings.TrimPrefix (strings.TrimSuffix "/" site.BaseURL) $href }}
{{- end -}}
{{- else if not (strings.Contains $href "/") -}}
{{ $url = index site.Params.links $href }}
{{- end -}}
{{ if not $url }}
{{- $href = strings.TrimPrefix "./" $href -}}
{{- if strings.Contains $href "#" }}
{{ $segments := split $href "#" }}
{{- if ne (len $segments) 2 }}
{{ errorf "Malformed path, expected one anchor '#' only: '%s' at %s" $href .Position -}}
{{ else }}
{{- $url = index $segments 0 -}}
{{- $anchor = index $segments 1 -}}
{{ if not $url }}
{{ $url = .Page.File.Path }}
{{ end }}
{{ end }}
{{ else }}
{{- $url = $href -}}
{{ end }}
{{ end }}
{{ if and $external (not (hasPrefix $url "http")) }}
{{ errorf "External link must start with 'http': %s" .Position -}}
{{ $error = true -}}
{{ end }}
{{- $isExternal := or (ne (urls.Parse (absURL $url)).Host (urls.Parse site.BaseURL).Host) $external -}}
{{- if not $isExternal -}}
{{ $ref := partial "utilities/GetPage.html" (dict "url" $url "page" .Page) }}
{{- if not $ref -}}
{{- errorf "Cannot find page: '%s' at %s" $url .Position -}}
{{- $error = true -}}
{{- end -}}
{{- end -}}
{{ with $anchor }}
{{ $url = printf "%s#%s" $url .}}
{{ end }}
<!-- Main code -->
{{- if not $error -}}
{{ partial "assets/link.html" (dict "destination" $url "text" $text "cue" $cue "tab" $tab "case" $case "external" $external "class" $class "page" .Page) }}
{{- end -}}