| 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/spf13/cast" |
| 22 |
) |
| 23 |
|
| 24 |
// New returns a new instance of the safe-namespaced template functions. |
| 25 |
func New() *Namespace { |
| 26 |
return &Namespace{} |
| 27 |
} |
| 28 |
|
| 29 |
// Namespace provides template functions for the "safe" namespace. |
| 30 |
type Namespace struct{} |
| 31 |
|
| 32 |
// CSS returns the string s as html/template CSS content. |
| 33 |
func (ns *Namespace) CSS(s any) (template.CSS, error) { |
| 34 |
ss, err := cast.ToStringE(s) |
| 35 |
return template.CSS(ss), err |
| 36 |
} |
| 37 |
|
| 38 |
// HTML returns the string s as html/template HTML content. |
| 39 |
func (ns *Namespace) HTML(s any) (template.HTML, error) { |
| 40 |
ss, err := cast.ToStringE(s) |
| 41 |
return template.HTML(ss), err |
| 42 |
} |
| 43 |
|
| 44 |
// HTMLAttr returns the string s as html/template HTMLAttr content. |
| 45 |
func (ns *Namespace) HTMLAttr(s any) (template.HTMLAttr, error) { |
| 46 |
ss, err := cast.ToStringE(s) |
| 47 |
return template.HTMLAttr(ss), err |
| 48 |
} |
| 49 |
|
| 50 |
// JS returns the given string as a html/template JS content. |
| 51 |
func (ns *Namespace) JS(s any) (template.JS, error) { |
| 52 |
ss, err := cast.ToStringE(s) |
| 53 |
return template.JS(ss), err |
| 54 |
} |
| 55 |
|
| 56 |
// JSStr returns the given string as a html/template JSStr content. |
| 57 |
func (ns *Namespace) JSStr(s any) (template.JSStr, error) { |
| 58 |
ss, err := cast.ToStringE(s) |
| 59 |
return template.JSStr(ss), err |
| 60 |
} |
| 61 |
|
| 62 |
// URL returns the string s as html/template URL content. |
| 63 |
func (ns *Namespace) URL(s any) (template.URL, error) { |
| 64 |
ss, err := cast.ToStringE(s) |
| 65 |
return template.URL(ss), err |
| 66 |
} |