New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
text/template: no nice way to escape/suppress newlines #9969
Comments
However this might work, it would need to be backward-compatible with existing templates. That rules out |
Good point. How about nunjucks system of adding a - at the start and/or end of a block to eat leading/trailing whitespace? Nunjucks does that: http://mozilla.github.io/nunjucks/templating.html#whitespace-control
|
Seems like a reasonable approach. Can you give me an example of where this might help, so that I can judge the feature in context? |
Sure, the thread had an example of generating a tsv file I think, but my so I have something that looks like:
{{with $mask := .BitMask}} Which produces a lot of empty lines. I have to put non-related things on
line Not sure if the dash character is the best choice, but something like that On Mon, Feb 23, 2015 at 10:12 PM, Andrew Gerrand notifications@github.com
|
I've also frequently run into this while generating code and been frustrated by it. |
The current way to avoid a newline is to do this:
which is a little verbose for such a minor signal. It would be helpful to have some way to signal that we don't want a newline.
Should produce (where
Hey @robpike what do you think? |
Could we add some kind of pre-template configuration options?
{{ option +line-continuation }}
or something like that.
and then we can just use the most natural syntax for line continuation:
line 1 \
line 2
It also preserves compatibility with existing templates.
we can also make the line continuation character (or character sequence)
configurable.
|
Or it can be a method on template, e.g. On Tue, Feb 24, 2015 at 7:32 PM, Minux Ma notifications@github.com wrote:
|
I don't propose it to be a method on Template is because
I think this configuration is better contained in the template
file itself, so that the code that uses the template doesn't
need to know whether the template uses that feature or not.
I will also seamlessly update existing code and templates.
Just recompile the code with Go 1.5 and you can start using
this feature in templates.
|
I expect it as a builtin function, for example. now:
use a builtin functin EAT_NEXT_NEWLINE:
|
I run into this almost every time I use |
I am using consul-template to generate text config files using a Go template. The templates can get quite complicated with nested ranges and conditionals. Making output result readable leads to ugly and unreadable code. Needs to be fixed at the earliest. |
+1 |
I'm also generating configuration which at some point will need to be read by humans. I really like the idea of |
We’ve used var (
src = `{{range .Items}} \
Hello, \
{{.Name}} \
{{end}}
`
t = template.Must(template.New("go").Parse(strings.Replace(src, "\\\n", "", -1)))
) https://github.com/zonedb/zonedb/blob/master/build/generate.go#L85 |
I agree that something like this would be useful. My biggest complaint with templates thus far is that they are hard to make human-readable without sacrificing the quality of the output. That said, I suspect that there may be a lot of unique cases. Eg in my case I only wanted to trim newlines, so I used the following: leading := regexp.MustCompile("(\n)*[{]{2}[-][ ]*")
tempBytes = leading.ReplaceAll(tempBytes, []byte("{{"))
trailing := regexp.MustCompile("[ ]*[-][}]{2}(\n)*")
tempBytes = trailing.ReplaceAll(tempBytes, []byte("}}")) If you do address this, it would be nice to have a little flexibility but I don't really know how far you can go without it snowballing into too much. |
+1 |
+1, this might help us write more readable code: Let's say we want to create this text: CREATE TABLE IF NOT EXISTS my.table (
key VARCHAR(100) PRIMARY KEY NOT NULL,
value1 INTEGER,
value2 INTEGER
); I had to: package main
import (
"bytes"
"fmt"
"html/template"
"log"
)
func main() {
queryStruct := struct {
SchemaName string
TableName string
Slice []map[string]string
LastIndex int
}{
"my",
"table",
[]map[string]string{
map[string]string{"key": "VARCHAR(100) PRIMARY KEY NOT NULL"},
map[string]string{"value1": "INTEGER"},
map[string]string{"value2": "INTEGER"},
},
2,
}
tb := new(bytes.Buffer)
if err := template.Must(template.New("tmpl").Parse(queryTmpl)).Execute(tb, queryStruct); err != nil {
log.Fatal(err)
}
fmt.Println(tb.String())
}
var queryTmpl = `CREATE TABLE IF NOT EXISTS {{.SchemaName}}.{{.TableName}} ({{$lastIndex := .LastIndex}}
{{range $index, $valueMap := .Slice}}{{if ne $lastIndex $index}}{{range $key, $value := $valueMap}} {{$key}} {{$value}},{{end}}
{{else}}{{range $key, $value := $valueMap}} {{$key}} {{$value}}{{end}}
{{end}}{{end}});` http://play.golang.org/p/gl5CJWVry7 Thanks, |
Just as a reference, Python Jinja's whitespace control is done with an optional global configuration to trim whitespace from lines with only a template block, as well as fine grained control based on the http://jinja.pocoo.org/docs/dev/templates/#whitespace-control The |
👍 for |
|
@robpike any thoughts about this? I just bumped into it again. I may be a princess, but this is definitely a pea. |
+1 for |
👍 +1 for {{-end}} |
Lines that only has code statements should probably not generate a newline at all. It is nice to keep them on a separate line for readability. Input: [1,2,3]
Result:
As for the other part {{-end}} seems similar to what Jinja does. So why not. |
+1. Both Ruby ERB and Jinja do somewhat similar things and I think it's an absolute requirement to have something similar in Go. Otherwise templating output looks stupid. Almost as stupid as this comment I'm leaving. |
+1 for ERB / Jinja style |
+1 for {{- end }} syntax, matches well with ERB templates |
+1 for {{- end }} |
+1 for ERB / Jinja style |
+1 for the suggested "{{- end}}" as well. |
CL https://golang.org/cl/14391 mentions this issue. |
…en actions Borrowing a suggestion from the issue listed below, we modify the lexer to trim spaces at the beginning (end) of a block of text if the action immediately before (after) is marked with a minus sign. To avoid parsing/lexing ambiguity, we require an ASCII space between the minus sign and the rest of the action. Thus: {{23 -}} < {{- 45}} produces the output 23<45 All the work is done in the lexer. The modification is invisible to the parser or any outside package (except I guess for noticing some gaps in the input if one tracks error positions). Thus it slips in without worry in text/template and html/template both. Fixes long-requested issue #9969. Change-Id: I3774be650bfa6370cb993d0899aa669c211de7b2 Reviewed-on: https://go-review.googlesource.com/14391 Reviewed-by: Andrew Gerrand <adg@golang.org>
Thanks! |
1 similar comment
Thanks! |
Wohoo, thanks! |
when will next release come? |
The next release is scheduled for February 1, 2016. |
This will be fantastic to have! |
The only difference are the extra newlines but that will have to wait until after Go 1.6 is out: golang/go#9969
This comment is too late..but I've only recently joined the word of go templating. Example:Text {{end}}The lines containing {{range.}} and {{end}} produce no actual output - so supress the blank line. |
This has been implemented, please see the go 1.6 release notes. |
and the link to the Go 1.6 release notes
|
@DSanthosh, you're commenting on a closed issue. We only use the issue tracker for bug reports, and don't track things once closed. For questions about Go, see https://golang.org/wiki/Questions. |
In many text/template scenarios, when creating text files (e.g. csv) for machine consumption, or text documents for human consumption, it's desirable to control the newlines output by the template. Currently this involves jumping through hoops by moving template tags around, making the template very unreadable. A simple e.g \ character at the end of a line would be nice to escape the newline so it doesn't end up in the output text, but the template tags can still be organized nicely in the template itself.
Seems there was already a request for this on go-nuts: https://groups.google.com/forum/#!topic/golang-nuts/H_d6P6av8nk
The text was updated successfully, but these errors were encountered: