safe.go (2341B)
1 // Copyright 2017 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 safe provides template functions for escaping untrusted content or
15 // encapsulating trusted content.
16 package safe
17
18 import (
19 "html/template"
20
21 "github.com/gohugoio/hugo/helpers"
22 "github.com/spf13/cast"
23 )
24
25 // New returns a new instance of the safe-namespaced template functions.
26 func New() *Namespace {
27 return &Namespace{}
28 }
29
30 // Namespace provides template functions for the "safe" namespace.
31 type Namespace struct{}
32
33 // CSS returns the string s as html/template CSS content.
34 func (ns *Namespace) CSS(s any) (template.CSS, error) {
35 ss, err := cast.ToStringE(s)
36 return template.CSS(ss), err
37 }
38
39 // HTML returns the string s as html/template HTML content.
40 func (ns *Namespace) HTML(s any) (template.HTML, error) {
41 ss, err := cast.ToStringE(s)
42 return template.HTML(ss), err
43 }
44
45 // HTMLAttr returns the string s as html/template HTMLAttr content.
46 func (ns *Namespace) HTMLAttr(s any) (template.HTMLAttr, error) {
47 ss, err := cast.ToStringE(s)
48 return template.HTMLAttr(ss), err
49 }
50
51 // JS returns the given string as a html/template JS content.
52 func (ns *Namespace) JS(s any) (template.JS, error) {
53 ss, err := cast.ToStringE(s)
54 return template.JS(ss), err
55 }
56
57 // JSStr returns the given string as a html/template JSStr content.
58 func (ns *Namespace) JSStr(s any) (template.JSStr, error) {
59 ss, err := cast.ToStringE(s)
60 return template.JSStr(ss), err
61 }
62
63 // URL returns the string s as html/template URL content.
64 func (ns *Namespace) URL(s any) (template.URL, error) {
65 ss, err := cast.ToStringE(s)
66 return template.URL(ss), err
67 }
68
69 // SanitizeURL returns the string s as html/template URL content.
70 func (ns *Namespace) SanitizeURL(s any) (string, error) {
71 ss, err := cast.ToStringE(s)
72 return helpers.SanitizeURL(ss), err
73 }