How can I control spaces after an action in html / template?

I have a problem with managing spaces and formatting html/template in readable mode. My templates look something like this:

layout.tmpl

 {{define "layout"}} <!DOCTYPE html> <html> <head> <title>{{.title}}</title> </head> <body> {{ template "body" . }} </body> </html> {{end}} 

body.tmpl

 {{define "body"}} {{ range .items }} {{.count}} items are made of {{.material}} {{end}} {{end}} 

code

 package main import ( "os" "text/template" ) type View struct { layout string body string } type Smap map[string]string func (self View) Render(data map[string]interface{}) { layout := self.layout + ".tmpl" body := self.body + ".tmpl" tmpl := template.Must(template.New("layout").ParseFiles(layout, body)) tmpl.ExecuteTemplate(os.Stdout, "layout", data) } func main() { view := View{ "layout", "body" } view.Render(map[string]interface{}{ "title": "stock", "items": []Smap{ Smap{ "count": "2", "material": "angora", }, Smap{ "count": "3", "material": "wool", }, }, }) } 

But this produces (note: there is a line above doctype):

 <!DOCTYPE html> <html> <head> <title>stock</title> </head> <body> 2 items are made of angora 3 items are made of wool </body> </html> 

I want to:

 <!DOCTYPE html> <html> <head> <title>stock</title> </head> <body> 2 items are made of angora 3 items are made of wool </body> </html> 

In other template languages, I can say things like

 [[- value -]] 

and spaces before and after the action are removed, but I don't see anything like it in html/template . Does this really mean that I have to make my templates unreadable, as shown below?

layout.tmpl

 {{define "layout"}}<!DOCTYPE html> <html> <head> <title>.title</title> </head> <body> {{ template "body" . }} </body> </html> {{end}} 

body.tmpl

 {{define "body"}}{{ range .items }}{{.count}} items are made of {{.material}} {{end}}{{end}} 
+6
source share
3 answers

You can use the space controller

 {{range .foos -}} // eats trailing whitespace <tr><td>do something</td></tr> {{- end}} // eats leading whitespace (\n from previous line) 
+5
source

Whitespace in this case has nothing to do with the visualized output in the user's browser, so managing it is not much different from aesthetics.

Alternatively, you can have beautifully formatted templates (which I would prefer) or partially beautifully formatted HTML (without nested indentation). Select one or a post to process HTML using any of the existing formats.

+2
source

Yes, spaces and lines are literally translated. If you have a line with just {{define}} or anything else that does not produce output, you will have an empty line in the parsed file.

Ideally, since you are using a template, you do not need to view or edit the output being analyzed. Use JSP / JSF for reference and look at the ugly output it gives you. Browse the source of most pages on the Internet; they are also ugly.

Good luck

+1
source

Source: https://habr.com/ru/post/948841/


All Articles