Join GitHub today
GitHub is home to over 50 million developers working together to host and review code, manage projects, and build software together.Sign up
GitHub is where the world builds software
Millions of developers and companies build, ship, and maintain their software on GitHub — the largest and most advanced development platform in the world.
text/template: Templates should be able to access variables outside them #17454
Templates cannot use variables defined outside them, like so:
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:
Note: See below for a correction.
You have to duplicate that shared data and push it down into each element of the slice:
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).
Your second example works fine for me:
The first example doesn't work because you are defining a block. You can think of blocks as subroutines; the variables from one block do not leak into the scope of the second block. This is specifically documented:
Thanks for pointing that out. Yes, the second example should be inside a define block. I think they should be in scope at block definition, not when they're applied/run.
The scenario I had in mind:
This won't work, but seems like it should, and it would be useful.
Okay, so look at this example then:
In that example, if the contents of the block had been
Remember that templates can be invoked without invoking their enclosing code.