Given this template snippet:
{{ $v := "init" }}
{{ if true }}
{{ $v := "changed" }}
{{ end }}
v: {{ $v }} {{/* => init */}}
The inner $v
is not visible on the outside. :=
does hint that this is a new variable.
Trying
{{ $v = "changed" }}
Gives
unexpected "=" in operand; missing space?
This is probably as designed, but it would be really nice if there was a way to get the changed $v
outside of the conditional.
This is the #1 template question we get over at Hugo (https://github.com/spf13/hugo). We have added a hack to workaround it for now ...
@bep can you please point where this hack located? Searched docs several times, but no luck...
Thanks!
@vanburg http://gohugo.io/extras/scratch/
@bep wow, how can I missed it?! Thanks!
@bep, could you explain, what is your workaround? How I can assign to $v variable different values depending on condition. tx.
@jupy ask here: http://discuss.gohugo.io/ This is the GO issue tracker.
Any update on this issue? It's such a simple issue that would make working with templates so much easier.
Wow, I'm amazed that it's been almost two years and this still doesn't work? I thought I was going crazy, not realizing it was a limitation — it seems so obvious. Looking forward to this!
Anything new?^^
Had a quick look. As @bep said, this seems to be by design - templates have no =
or assignment operator. Not in the package godoc, nor anywhere in the text/template/parser package.
This issue isn't a proposal, and it was set to Unplanned which means "might be fixed at some point", so I'll assume that there is no reason to not add the feature. It also seems logical to have it, as the template package does speak of "variables" and the :=
operator can lead one to think that =
is available too.
I'll try to have a CL for 1.11 - reviewers welcome once it's up.
Change https://golang.org/cl/84480 mentions this issue: text/template: add variable assignments
The 1.11 tree is now open and I am still looking for reviewers - any takers from the emoji party above?
In the CL I posted, Rob pointed out how this idea was never formally a proposal, so it was never reviewed nor accepted. In my earlier comment I explained why I assumed that this issue could be worked on, but I think I was a bit too optimistic in my thinking that it had already been reviewed.
For the time being, I've repurposed the issue as a proposal, and hopefully the proposal review team will get to it soon.
I half-remember putting this into a local fork a long time ago. It does seem like something you'd want if you write any sizable amount of templates.
Great; back to the CL :) I will reply to Rob's concerns there soon. More reviewers are still needed.
Most helpful comment
Great; back to the CL :) I will reply to Rob's concerns there soon. More reviewers are still needed.