page__ref.go (2643B)
1 // Copyright 2019 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package hugolib
15
16 import (
17 "fmt"
18
19 "github.com/gohugoio/hugo/common/text"
20
21 "github.com/mitchellh/mapstructure"
22 )
23
24 func newPageRef(p *pageState) pageRef {
25 return pageRef{p: p}
26 }
27
28 type pageRef struct {
29 p *pageState
30 }
31
32 func (p pageRef) Ref(argsm map[string]any) (string, error) {
33 return p.ref(argsm, p.p)
34 }
35
36 func (p pageRef) RefFrom(argsm map[string]any, source any) (string, error) {
37 return p.ref(argsm, source)
38 }
39
40 func (p pageRef) RelRef(argsm map[string]any) (string, error) {
41 return p.relRef(argsm, p.p)
42 }
43
44 func (p pageRef) RelRefFrom(argsm map[string]any, source any) (string, error) {
45 return p.relRef(argsm, source)
46 }
47
48 func (p pageRef) decodeRefArgs(args map[string]any) (refArgs, *Site, error) {
49 var ra refArgs
50 err := mapstructure.WeakDecode(args, &ra)
51 if err != nil {
52 return ra, nil, nil
53 }
54
55 s := p.p.s
56
57 if ra.Lang != "" && ra.Lang != p.p.s.Language().Lang {
58 // Find correct site
59 found := false
60 for _, ss := range p.p.s.h.Sites {
61 if ss.Lang() == ra.Lang {
62 found = true
63 s = ss
64 }
65 }
66
67 if !found {
68 p.p.s.siteRefLinker.logNotFound(ra.Path, fmt.Sprintf("no site found with lang %q", ra.Lang), nil, text.Position{})
69 return ra, nil, nil
70 }
71 }
72
73 return ra, s, nil
74 }
75
76 func (p pageRef) ref(argsm map[string]any, source any) (string, error) {
77 args, s, err := p.decodeRefArgs(argsm)
78 if err != nil {
79 return "", fmt.Errorf("invalid arguments to Ref: %w", err)
80 }
81
82 if s == nil {
83 return p.p.s.siteRefLinker.notFoundURL, nil
84 }
85
86 if args.Path == "" {
87 return "", nil
88 }
89
90 return s.refLink(args.Path, source, false, args.OutputFormat)
91 }
92
93 func (p pageRef) relRef(argsm map[string]any, source any) (string, error) {
94 args, s, err := p.decodeRefArgs(argsm)
95 if err != nil {
96 return "", fmt.Errorf("invalid arguments to Ref: %w", err)
97 }
98
99 if s == nil {
100 return p.p.s.siteRefLinker.notFoundURL, nil
101 }
102
103 if args.Path == "" {
104 return "", nil
105 }
106
107 return s.refLink(args.Path, source, true, args.OutputFormat)
108 }
109
110 type refArgs struct {
111 Path string
112 Lang string
113 OutputFormat string
114 }