html/template's {{- -}} does not trim whitespace for javascript boolean and number variables?

933 views
Skip to first unread message

Nazri Ramliy

unread,
Jan 5, 2017, 1:40:23 AM1/5/17
to golan...@googlegroups.com
Hi,

This looks like a bug in the html/template package:
https://play.golang.org/p/TWaBZ4MwOd

I expect that the {{- and -}} would trim the spaces surrounding the
variable values like this:

<script>
var s =string;
var b =true;
var i =42;
var f =42.2;
</script>

but instead the output is:

<script>
var s ="string";
var b = true ;
var i = 42 ;
var f = 42.2 ;
</script>

Notice that only the spaces surrounding the "string" value is trimmed,
and for the others the spaces seem to have been collapsed into a
single space.

nazri

Ingo Oeser

unread,
Jan 5, 2017, 3:07:07 AM1/5/17
to golang-dev
Please file an issue, if you think this is a bug.

Rob Pike

unread,
Jan 5, 2017, 6:52:05 AM1/5/17
to Ingo Oeser, golang-dev
It works as expected with text/template, so it's a bug in html/template. Please file an issue.

On Thu, Jan 5, 2017 at 7:07 PM, 'Ingo Oeser' via golang-dev <golan...@googlegroups.com> wrote:
Please file an issue, if you think this is a bug.

--
You received this message because you are subscribed to the Google Groups "golang-dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-dev+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

kenny...@gmail.com

unread,
Jan 5, 2017, 10:28:22 AM1/5/17
to golang-dev
I don't think this is related to -}} if you remove the - and spaces you get the same result, it is related to this text being treated as javascript. Might be worth logging a bug about the formatting of the js vars as that seems inconsistent between the string var and the others. 

Josh Lubawy

unread,
Jan 5, 2017, 10:28:22 AM1/5/17
to golang-dev
I ran into this issue myself recently, but I believe this is intended since values in Javascript are escaped in templates (see 'src/html/template/js.go:jsValEscaper').

If you trust the input you can prevent this escaping by casting the string value of whatever you are trying to emit to a template.JS type.


Thanks,
Josh
Reply all
Reply to author
Forward
0 new messages