// NewTemplateRenderable returns a new Renderable
195772
func NewTemplateRenderable(content string) (*TemplateRenderable, error) {
	tl, err := template.New("").Parse(content)
	if err != nil {
		return nil, err
	}

	tr := TemplateRenderable{
		tmpl:  tl,
		cache: bytes.NewBuffer([]byte{}),
	}

	return &tr, nil
}
1017436
func (b *builder) renderJobTemplates(
	releaseJobs []bireljob.Job,
	releaseJobProperties map[string]*biproperty.Map,
	jobProperties biproperty.Map,
	globalProperties biproperty.Map,
	deploymentName string,
	address string,
	stage biui.Stage,
) (renderedJobs, error) {
	var (
		renderedJobListArchive bitemplate.RenderedJobListArchive
		blobID                 string
	)
	err := stage.Perform("Rendering job templates", func() error {
		renderedJobList, err := b.jobListRenderer.Render(releaseJobs, releaseJobProperties, jobProperties, globalProperties, deploymentName, address)
		if err != nil {
			return err
		}
		defer renderedJobList.DeleteSilently()

		renderedJobListArchive, err = b.renderedJobListCompressor.Compress(renderedJobList)
		if err != nil {
			return bosherr.WrapError(err, "Compressing rendered job templates")
		}
		defer renderedJobListArchive.DeleteSilently()

		blobID, err = b.blobstore.Add(renderedJobListArchive.Path())
		if err != nil {
			return bosherr.WrapErrorf(err, "Uploading rendered job template archive '%s' to the blobstore", renderedJobListArchive.Path())
		}

		return nil
	})
	if err != nil {
		return renderedJobs{}, err
	}

	return renderedJobs{
		BlobstoreID: blobID,
		Archive:     renderedJobListArchive,
	}, nil
}
367096
func newTemplateInstances(c *TemplateClient, namespace string) *templateInstances {
	return &templateInstances{
		client: c.RESTClient(),
		ns:     namespace,
	}
}
387748
func (tmpl PongoTemplate) Render(wr io.Writer, arg interface{}) (err error) {
	gls.With(gls.Values(map[interface{}]interface{}{"data": arg}), func() {
		err = tmpl.template.ExecuteWriter(p2.Context(arg.(map[string]interface{})), wr)
		if nil != err {
			if e, ok := err.(*p2.Error); ok {
				rerr := &revel.Error{
					Title:       "Template Execution Error",
					Path:        tmpl.TemplateName,
					Description: e.Error(),
					Line:        e.Line,
				}
				if revel.DevMode {
					rerr.SourceLines = tmpl.Content()
				}
				err = rerr
			}
		}
	})
	return err
}
638452
func (ct *CompiledTemplate) Render(name string, source structs.QuerySource) (*structs.PreparedQuery, error) {
	// Make it "safe" to render a default structure.
	if ct == nil {
		return nil, fmt.Errorf("Cannot render an uncompiled template")
	}

	// Start with a fresh, detached copy of the original so we don't disturb
	// the prototype.
	dup, err := copystructure.Copy(ct.query)
	if err != nil {
		return nil, err
	}
	query, ok := dup.(*structs.PreparedQuery)
	if !ok {
		return nil, fmt.Errorf("Failed to copy query")
	}

	// Run the regular expression, if provided. We execute on a copy here
	// to avoid internal lock contention because we expect this to be called
	// from multiple goroutines.
	var matches []string
	if ct.re != nil {
		re := ct.re.Copy()
		matches = re.FindStringSubmatch(name)
	}

	// Create a safe match function that can't fail at run time. It will
	// return an empty string for any invalid input.
	match := ast.Function{
		ArgTypes:   []ast.Type{ast.TypeInt},
		ReturnType: ast.TypeString,
		Variadic:   false,
		Callback: func(inputs []interface{}) (interface{}, error) {
			i, ok := inputs[0].(int)
			if ok && i >= 0 && i < len(matches) {
				return matches[i], nil
			}
			return "", nil
		},
	}

	// Build up the HIL evaluation context.
	config := &hil.EvalConfig{
		GlobalScope: &ast.BasicScope{
			VarMap: map[string]ast.Variable{
				"name.full": ast.Variable{
					Type:  ast.TypeString,
					Value: name,
				},
				"name.prefix": ast.Variable{
					Type:  ast.TypeString,
					Value: query.Name,
				},
				"name.suffix": ast.Variable{
					Type:  ast.TypeString,
					Value: strings.TrimPrefix(name, query.Name),
				},
				"agent.segment": ast.Variable{
					Type:  ast.TypeString,
					Value: source.Segment,
				},
			},
			FuncMap: map[string]ast.Function{
				"match": match,
			},
		},
	}

	// Run through the Service sub-structure and evaluate all the strings
	// as HIL.
	eval := func(path string, v reflect.Value) error {
		tree, ok := ct.trees[path]
		if !ok {
			return nil
		}

		res, err := hil.Eval(tree, config)
		if err != nil {
			return fmt.Errorf("Bad evaluation for '%s' in Service%s: %s", v.String(), path, err)
		}
		if res.Type != hil.TypeString {
			return fmt.Errorf("Expected Service%s field to be a string, got %s", path, res.Type)
		}

		v.SetString(res.Value.(string))
		return nil
	}
	if err := walk(&query.Service, eval); err != nil {
		return nil, err
	}

	if ct.removeEmptyTags {
		tags := make([]string, 0, len(query.Service.Tags))
		for _, tag := range query.Service.Tags {
			if tag != "" {
				tags = append(tags, tag)
			}
		}
		query.Service.Tags = tags
	}

	return query, nil
}
226831
func (set *TemplateSet) RenderTemplateString(s string, ctx Context) (string, error) {
	set.firstTemplateCreated = true

	tpl := Must(set.FromString(s))
	result, err := tpl.Execute(ctx)
	if err != nil {
		return "", err
	}
	return result, nil
}
1188221
func NewTable(title string) *Panel {
	if title == "" {
		title = "Panel Title"
	}
	render := "flot"
	return &Panel{
		commonPanel: commonPanel{
			OfType:   TableType,
			Title:    title,
			Type:     "table",
			Renderer: &render,
			IsNew:    true},
		TablePanel: &TablePanel{}}
}
1229006
func NewTemplate(separator string, pattern string, defaultTags map[string]string) (*Template, error) {
	parts := strings.Split(pattern, separator)
	hasMeasurement := false
	template := &Template{
		separator:   separator,
		parts:       parts,
		defaultTags: defaultTags,
	}

	for _, part := range parts {
		if strings.HasPrefix(part, "measurement") {
			hasMeasurement = true
		}
		if part == "measurement*" {
			template.greedyMeasurement = true
		} else if part == "field*" {
			template.greedyField = true
		}
	}

	if !hasMeasurement {
		return nil, fmt.Errorf("no measurement specified for template. %q", pattern)
	}

	return template, nil
}
1251763
func NewTemplateEngine(root string) *TemplateEngine {
	return &TemplateEngine{
		cache:           map[string]*template.Template{},
		templWithLayout: map[string][]string{},
		root:            root,
	}
}
1132391
func (gotmpl GoTemplate) Render(wr io.Writer, arg interface{}) error {
	return gotmpl.Execute(wr, arg)
}
1096799
func (acetmpl AceTemplate) Render(wr io.Writer, arg interface{}) error {
	// We can redirect this render to another template if the arguments contain ace_content in them
	if argmap, ok := arg.(map[string]interface{}); ok {
		if acecontentraw, ok := argmap["ace-inner"]; ok {
			acecontent := acecontentraw.(string)
			newtemplatename := acetmpl.TemplateName + "-" + acecontent
			// Now lookup the template again
			if _, ok := acetmpl.engine.templatesByName[newtemplatename]; !ok {
				if inner, ok := acetmpl.engine.templatesByName[acecontent]; !ok {
					return fmt.Errorf("Inner content %s not found in ace templates", acecontent)
				} else {
					acetmpl.engine.templatesByName[newtemplatename] = &AceTemplate{
						File:         acetmpl.File,
						Inner:        inner.File,
						engine:       acetmpl.engine,
						TemplateView: acetmpl.TemplateView}
				}

			}
			return acetmpl.engine.templatesByName[newtemplatename].renderInternal(wr, arg)
		}
	}
	return acetmpl.renderInternal(wr, arg)
}
515952
func (tm *TaskTemplateManager) handleFirstRender() {
	// missingDependencies is the set of missing dependencies.
	var missingDependencies map[string]struct{}

	// eventTimer is used to trigger the firing of an event showing the missing
	// dependencies.
	eventTimer := time.NewTimer(tm.config.MaxTemplateEventRate)
	if !eventTimer.Stop() {
		<-eventTimer.C
	}

	// outstandingEvent tracks whether there is an outstanding event that should
	// be fired.
	outstandingEvent := false

	// Wait till all the templates have been rendered
WAIT:
	for {
		select {
		case <-tm.shutdownCh:
			return
		case err, ok := <-tm.runner.ErrCh:
			if !ok {
				continue
			}

			tm.config.Lifecycle.Kill(context.Background(),
				structs.NewTaskEvent(structs.TaskKilling).
					SetFailsTask().
					SetDisplayMessage(fmt.Sprintf("Template failed: %v", err)))
		case <-tm.runner.TemplateRenderedCh():
			// A template has been rendered, figure out what to do
			events := tm.runner.RenderEvents()

			// Not all templates have been rendered yet
			if len(events) < len(tm.lookup) {
				continue
			}

			for _, event := range events {
				// This template hasn't been rendered
				if event.LastWouldRender.IsZero() {
					continue WAIT
				}
			}

			break WAIT
		case <-tm.runner.RenderEventCh():
			events := tm.runner.RenderEvents()
			joinedSet := make(map[string]struct{})
			for _, event := range events {
				missing := event.MissingDeps
				if missing == nil {
					continue
				}

				for _, dep := range missing.List() {
					joinedSet[dep.String()] = struct{}{}
				}
			}

			// Check to see if the new joined set is the same as the old
			different := len(joinedSet) != len(missingDependencies)
			if !different {
				for k := range joinedSet {
					if _, ok := missingDependencies[k]; !ok {
						different = true
						break
					}
				}
			}

			// Nothing to do
			if !different {
				continue
			}

			// Update the missing set
			missingDependencies = joinedSet

			// Update the event timer channel
			if !outstandingEvent {
				// We got new data so reset
				outstandingEvent = true
				eventTimer.Reset(tm.config.MaxTemplateEventRate)
			}
		case <-eventTimer.C:
			if missingDependencies == nil {
				continue
			}

			// Clear the outstanding event
			outstandingEvent = false

			// Build the missing set
			missingSlice := make([]string, 0, len(missingDependencies))
			for k := range missingDependencies {
				missingSlice = append(missingSlice, k)
			}
			sort.Strings(missingSlice)

			if l := len(missingSlice); l > missingDepEventLimit {
				missingSlice[missingDepEventLimit] = fmt.Sprintf("and %d more", l-missingDepEventLimit)
				missingSlice = missingSlice[:missingDepEventLimit+1]
			}

			missingStr := strings.Join(missingSlice, ", ")
			tm.config.Events.EmitEvent(structs.NewTaskEvent(consulTemplateSourceName).SetDisplayMessage(fmt.Sprintf("Missing: %s", missingStr)))
		}
	}
}
852217
func NewTemplate(input string) (*Template, error) {
	hm, err := NewHelperMap()
	if err != nil {
		return nil, errors.WithStack(err)
	}
	t := &Template{
		Input:   input,
		Helpers: hm,
	}
	err = t.Parse()
	if err != nil {
		return t, errors.WithStack(err)
	}
	return t, nil
}
663375
func NewTemplate(context *context.Context) *Template {
	tpl := new(Template)
	tpl.Context = context
	return tpl
}
995636
func (c *Client) PrepareTemplate(p *PrepareTemplateParameter) (*Template, error) {
	obj, err := c.Request("prepareTemplate", convertParamToMap(p))
	if err != nil {
		return nil, err
	}
	return obj.(*Template), err
}
640322
func RenderTemplateToStream(output io.Writer, srcPath []string, data interface{}) (err error) {
	tmpl, err := template.ParseFiles(srcPath...)
	if err != nil {
		return NewBuildIfError(err, "Failed to parse template "+srcPath[0])
	}

	err = tmpl.Execute(output, data)
	if err != nil {
		return NewBuildIfError(err, "Failed to render template "+srcPath[0])
	}
	return
}
101880
func newTemplates(c *TemplateClient, namespace string) *templates {
	return &templates{
		client: c.RESTClient(),
		ns:     namespace,
	}
}