encoding.go (2478B)
1 // Copyright 2020 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 encoding provides template functions for encoding content.
15 package encoding
16
17 import (
18 "encoding/base64"
19 "encoding/json"
20 "errors"
21 "html/template"
22
23 "github.com/gohugoio/hugo/common/maps"
24 "github.com/spf13/cast"
25 )
26
27 // New returns a new instance of the encoding-namespaced template functions.
28 func New() *Namespace {
29 return &Namespace{}
30 }
31
32 // Namespace provides template functions for the "encoding" namespace.
33 type Namespace struct{}
34
35 // Base64Decode returns the base64 decoding of the given content.
36 func (ns *Namespace) Base64Decode(content any) (string, error) {
37 conv, err := cast.ToStringE(content)
38 if err != nil {
39 return "", err
40 }
41
42 dec, err := base64.StdEncoding.DecodeString(conv)
43 return string(dec), err
44 }
45
46 // Base64Encode returns the base64 encoding of the given content.
47 func (ns *Namespace) Base64Encode(content any) (string, error) {
48 conv, err := cast.ToStringE(content)
49 if err != nil {
50 return "", err
51 }
52
53 return base64.StdEncoding.EncodeToString([]byte(conv)), nil
54 }
55
56 // Jsonify encodes a given object to JSON. To pretty print the JSON, pass a map
57 // or dictionary of options as the first argument. Supported options are
58 // "prefix" and "indent". Each JSON element in the output will begin on a new
59 // line beginning with prefix followed by one or more copies of indent according
60 // to the indentation nesting.
61 func (ns *Namespace) Jsonify(args ...any) (template.HTML, error) {
62 var (
63 b []byte
64 err error
65 )
66
67 switch len(args) {
68 case 0:
69 return "", nil
70 case 1:
71 b, err = json.Marshal(args[0])
72 case 2:
73 var opts map[string]string
74
75 opts, err = maps.ToStringMapStringE(args[0])
76 if err != nil {
77 break
78 }
79
80 b, err = json.MarshalIndent(args[1], opts["prefix"], opts["indent"])
81 default:
82 err = errors.New("too many arguments to jsonify")
83 }
84
85 if err != nil {
86 return "", err
87 }
88
89 return template.HTML(b), nil
90 }