~nromdotcom/gemif

ref: f1ef4d543cc010bb97d0d825503ff0ece1841ed7 gemif/pkg/scenerenderer/scenerenderer.go -rw-r--r-- 947 bytes
f1ef4d54Norm MacLennan README updates for new features 1 year, 8 months 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
package scenerenderer

import (
	"bytes"
	"fmt"
	"gemif/pkg/gamemanager"
	"text/template"
)

// 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
}