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