mirror of
https://github.com/gohugoio/hugo.git
synced 2025-08-18 21:11:19 +02:00
@@ -14,6 +14,7 @@
|
||||
package types
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"html/template"
|
||||
|
||||
"github.com/spf13/cast"
|
||||
@@ -59,10 +60,20 @@ func TypeToString(v interface{}) (string, bool) {
|
||||
|
||||
// ToString converts v to a string.
|
||||
func ToString(v interface{}) string {
|
||||
s, _ := ToStringE(v)
|
||||
return s
|
||||
}
|
||||
|
||||
// ToStringE converts v to a string.
|
||||
func ToStringE(v interface{}) (string, error) {
|
||||
if s, ok := TypeToString(v); ok {
|
||||
return s
|
||||
return s, nil
|
||||
}
|
||||
|
||||
return cast.ToString(v)
|
||||
|
||||
switch s := v.(type) {
|
||||
case json.RawMessage:
|
||||
return string(s), nil
|
||||
default:
|
||||
return cast.ToStringE(v)
|
||||
}
|
||||
}
|
||||
|
@@ -14,6 +14,7 @@
|
||||
package types
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
qt "github.com/frankban/quicktest"
|
||||
@@ -27,3 +28,11 @@ func TestToStringSlicePreserveString(t *testing.T) {
|
||||
c.Assert(ToStringSlicePreserveString(nil), qt.IsNil)
|
||||
|
||||
}
|
||||
|
||||
func TestToString(t *testing.T) {
|
||||
c := qt.New(t)
|
||||
|
||||
c.Assert(ToString([]byte("Hugo")), qt.Equals, "Hugo")
|
||||
c.Assert(ToString(json.RawMessage("Hugo")), qt.Equals, "Hugo")
|
||||
|
||||
}
|
||||
|
Reference in New Issue
Block a user