Skip to content

text/template: Templates should be able to access variables outside them #17454

@willfaught

Description

@willfaught

Templates cannot use variables defined outside them, like so:

{{$foo := .Foo}}
{{define "bar"}} {{$foo}} {{end}} {{/* error: unknown variable "foo" */}}

This means the template parameter pipeline must contain all the data needed by the template.

So if you've got a slice, and all the elements share some data, and in an iteration of the slice you want to pass everything about an element to a template, you can't factor that data out into a surrounding struct and then pull it into templates with variables:

type Names struct {
    First string
    Last []string
}

{{$first := .Names.First}}
{{range .Names.Last}} {{$first}} {{.}} {{end}} {{/* error: unknown variable "first" */}}

Note: See below for a correction.

You have to duplicate that shared data and push it down into each element of the slice:

type Name struct {
    First string
    Last string
}

{{range .Names}} {{.First}} {{.Last}} {{end}} {{/* .First is the same for all iterations */}}

I'm lazy and I don't want to do this. [Insert arguments here about DRY, compose-ability, simplicity, power, lexical scoping, etc.]

Note that this ability to reference outside variables isn't all that different from the ability to reference outside templates within the same "scope" (text/template doc term, not mine).

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions