diff options
author | Marek Janda <nyx@nyx.cz> | 2015-08-02 07:00:43 +0200 |
---|---|---|
committer | Bjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com> | 2015-08-02 17:23:36 +0200 |
commit | 4bed69629e55f7292505a74e8437a5a05ddf9a22 (patch) | |
tree | 66adf9cf00fd096030dec9b5e38fc9aea4cef174 /hugolib/scratch.go | |
parent | 8d28686edcf19b5dd067482b72fdc1b93c99ef7f (diff) |
Add map support to scratch
Diffstat (limited to 'hugolib/scratch.go')
-rw-r--r-- | hugolib/scratch.go | 36 |
1 files changed, 36 insertions, 0 deletions
diff --git a/hugolib/scratch.go b/hugolib/scratch.go index 0f5c4b484..16d1c1440 100644 --- a/hugolib/scratch.go +++ b/hugolib/scratch.go @@ -15,6 +15,7 @@ package hugolib import ( "github.com/spf13/hugo/helpers" + "sort" ) // Scratch is a writable context used for stateful operations in Page/Node rendering. @@ -52,6 +53,41 @@ func (c *Scratch) Get(key string) interface{} { return c.values[key] } +// SetInMap stores a value to a map with the given key in the Node context. +// This map can later be retrieved with GetSortedMapValues. +func (c *Scratch) SetInMap(key string, mapKey string, value interface{}) string { + _, found := c.values[key] + if !found { + c.values[key] = make(map[string]interface{}) + } + + c.values[key].(map[string]interface{})[mapKey] = value + return "" +} + +// GetSortedMapValues returns a sorted map previously filled with SetInMap +func (c *Scratch) GetSortedMapValues(key string) interface{} { + if c.values[key] == nil { + return nil + } + + unsortedMap := c.values[key].(map[string]interface{}) + + var keys []string + for mapKey, _ := range unsortedMap { + keys = append(keys, mapKey) + } + + sort.Strings(keys) + + sortedArray := make([]interface{}, len(unsortedMap)) + for i, mapKey := range keys { + sortedArray[i] = unsortedMap[mapKey] + } + + return sortedArray +} + func newScratch() *Scratch { return &Scratch{values: make(map[string]interface{})} } |