github.com/graemephi/kahugo@v0.62.3-0.20211121071557-d78c0423784d/tpl/safe/safe.go (about) 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 a given string as html/template CSS content. 34 func (ns *Namespace) CSS(a interface{}) (template.CSS, error) { 35 s, err := cast.ToStringE(a) 36 return template.CSS(s), err 37 } 38 39 // HTML returns a given string as html/template HTML content. 40 func (ns *Namespace) HTML(a interface{}) (template.HTML, error) { 41 s, err := cast.ToStringE(a) 42 return template.HTML(s), err 43 } 44 45 // HTMLAttr returns a given string as html/template HTMLAttr content. 46 func (ns *Namespace) HTMLAttr(a interface{}) (template.HTMLAttr, error) { 47 s, err := cast.ToStringE(a) 48 return template.HTMLAttr(s), err 49 } 50 51 // JS returns the given string as a html/template JS content. 52 func (ns *Namespace) JS(a interface{}) (template.JS, error) { 53 s, err := cast.ToStringE(a) 54 return template.JS(s), err 55 } 56 57 // JSStr returns the given string as a html/template JSStr content. 58 func (ns *Namespace) JSStr(a interface{}) (template.JSStr, error) { 59 s, err := cast.ToStringE(a) 60 return template.JSStr(s), err 61 } 62 63 // URL returns a given string as html/template URL content. 64 func (ns *Namespace) URL(a interface{}) (template.URL, error) { 65 s, err := cast.ToStringE(a) 66 return template.URL(s), err 67 } 68 69 // SanitizeURL returns a given string as html/template URL content. 70 func (ns *Namespace) SanitizeURL(a interface{}) (string, error) { 71 s, err := cast.ToStringE(a) 72 return helpers.SanitizeURL(s), err 73 }