mirror of
https://github.com/gohugoio/hugo.git
synced 2025-08-16 20:53:59 +02:00
tpl: Extend Jsonify to support options map
Add support for prefix and indent options used by json.MarshalIndent from the Go stdlib.
This commit is contained in:
committed by
Bjørn Erik Pedersen
parent
1bc93021e3
commit
8568928aa8
@@ -1,4 +1,4 @@
|
||||
// Copyright 2017 The Hugo Authors. All rights reserved.
|
||||
// Copyright 2020 The Hugo Authors. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
@@ -52,8 +52,11 @@ func (ns *Namespace) Base64Encode(content interface{}) (string, error) {
|
||||
return base64.StdEncoding.EncodeToString([]byte(conv)), nil
|
||||
}
|
||||
|
||||
// Jsonify encodes a given object to JSON. To pretty print the JSON, pass an
|
||||
// optional first argument of the indent string, such as " ".
|
||||
// Jsonify encodes a given object to JSON. To pretty print the JSON, pass a map
|
||||
// or dictionary of options as the first argument. Supported options are
|
||||
// "prefix" and "indent". Each JSON element in the output will begin on a new
|
||||
// line beginning with prefix followed by one or more copies of indent according
|
||||
// to the indentation nesting.
|
||||
func (ns *Namespace) Jsonify(args ...interface{}) (template.HTML, error) {
|
||||
var (
|
||||
b []byte
|
||||
@@ -66,14 +69,14 @@ func (ns *Namespace) Jsonify(args ...interface{}) (template.HTML, error) {
|
||||
case 1:
|
||||
b, err = json.Marshal(args[0])
|
||||
case 2:
|
||||
var indent string
|
||||
var opts map[string]string
|
||||
|
||||
indent, err = cast.ToStringE(args[0])
|
||||
opts, err = cast.ToStringMapStringE(args[0])
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
|
||||
b, err = json.MarshalIndent(args[1], "", indent)
|
||||
b, err = json.MarshalIndent(args[1], opts["prefix"], opts["indent"])
|
||||
default:
|
||||
err = errors.New("too many arguments to jsonify")
|
||||
}
|
||||
|
Reference in New Issue
Block a user