github.com/hairyhenderson/gomplate/v4@v4.0.0-pre-2.0.20240520121557-362f058f0c93/context.go (about)

     1  package gomplate
     2  
     3  import (
     4  	"context"
     5  	"os"
     6  	"strings"
     7  
     8  	"github.com/hairyhenderson/gomplate/v4/data"
     9  )
    10  
    11  // context for templates
    12  type tmplctx map[string]interface{}
    13  
    14  // Env - Map environment variables for use in a template
    15  func (c *tmplctx) Env() map[string]string {
    16  	env := make(map[string]string)
    17  	for _, i := range os.Environ() {
    18  		sep := strings.Index(i, "=")
    19  		env[i[0:sep]] = i[sep+1:]
    20  	}
    21  	return env
    22  }
    23  
    24  // createTmplContext reads the datasources for the given aliases
    25  func createTmplContext(
    26  	ctx context.Context, aliases []string,
    27  	//nolint:staticcheck
    28  	d *data.Data,
    29  ) (interface{}, error) {
    30  	// we need to inject the current context into the Data value, because
    31  	// the Datasource method may need it
    32  	// TODO: remove this before v4
    33  	if d != nil {
    34  		d.Ctx = ctx
    35  	}
    36  
    37  	var err error
    38  	tctx := &tmplctx{}
    39  	for _, a := range aliases {
    40  		if a == "." {
    41  			return d.Datasource(a)
    42  		}
    43  		(*tctx)[a], err = d.Datasource(a)
    44  		if err != nil {
    45  			return nil, err
    46  		}
    47  	}
    48  	return tctx, nil
    49  }