github.com/shohhei1126/hugo@v0.42.2-0.20180623210752-3d5928889ad7/tpl/encoding/encoding.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 encoding
    15  
    16  import (
    17  	"encoding/base64"
    18  	"encoding/json"
    19  	"html/template"
    20  
    21  	"github.com/spf13/cast"
    22  )
    23  
    24  // New returns a new instance of the encoding-namespaced template functions.
    25  func New() *Namespace {
    26  	return &Namespace{}
    27  }
    28  
    29  // Namespace provides template functions for the "encoding" namespace.
    30  type Namespace struct{}
    31  
    32  // Base64Decode returns the base64 decoding of the given content.
    33  func (ns *Namespace) Base64Decode(content interface{}) (string, error) {
    34  	conv, err := cast.ToStringE(content)
    35  	if err != nil {
    36  		return "", err
    37  	}
    38  
    39  	dec, err := base64.StdEncoding.DecodeString(conv)
    40  	return string(dec), err
    41  }
    42  
    43  // Base64Encode returns the base64 encoding of the given content.
    44  func (ns *Namespace) Base64Encode(content interface{}) (string, error) {
    45  	conv, err := cast.ToStringE(content)
    46  	if err != nil {
    47  		return "", err
    48  	}
    49  
    50  	return base64.StdEncoding.EncodeToString([]byte(conv)), nil
    51  }
    52  
    53  // Jsonify encodes a given object to JSON.
    54  func (ns *Namespace) Jsonify(v interface{}) (template.HTML, error) {
    55  	b, err := json.Marshal(v)
    56  	if err != nil {
    57  		return "", err
    58  	}
    59  
    60  	return template.HTML(b), nil
    61  }