~nromdotcom/gemif

ref: 914458c58f6158ecb8e30fdfc595e50df9e5eaba gemif/pkg/scenerenderer/scenerenderer.go -rw-r--r-- 970 bytes
914458c5Norm MacLennan Update to fully-qualified module path to enable go get-ing 1 year, 1 month ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package scenerenderer

import (
	"bytes"
	"fmt"
	"text/template"

	"git.sr.ht/~nromdotcom/gemif/pkg/gamemanager"
)

// Template contains the room templates.
type Template struct {
	templates *template.Template
}

// New makes a new set of templates for room descriptions.
func New() Template {
	return Template{
		template.New(""),
	}
}

// ExecuteTemplate executes a rooms description template and returns a string.
func (t *Template) ExecuteTemplate(state gamemanager.GameState, tmpl string) (string, error) {
	templateName := fmt.Sprintf("%s%s", state.StoryID, state.CurrentRoom)
	roomTmpl := t.templates.Lookup(templateName)

	if roomTmpl == nil {
		template.Must(t.templates.New(templateName).Parse(tmpl))
	}

	var compiledDesc bytes.Buffer
	if compileErr := t.templates.ExecuteTemplate(&compiledDesc, templateName, state); compileErr != nil {
		return "", fmt.Errorf("could not construct room description: %w", compileErr)
	}

	return compiledDesc.String(), nil
}