2013-07-06 26 views
5

我遇到了控制空白的問題,仍然以可讀的方式格式化html/template模板。我的模板看起來財產以後這樣的:如何在HTML /模板中的操作後控制空白?

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}} 

代碼

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", 
      }, 
     }, 
    }) 
} 

但產生(注:上面有一條線文檔類型):

<!DOCTYPE html> 
<html> 
    <head> 
     <title>stock</title> 
    </head> 
    <body> 


2 items are made of angora 

3 items are made of wool 


    </body> 
</html> 

我要的是:

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

在其他的模板語言,我可以說這樣的話

[[- value -]] 

前和作用後的空白被剝離,但我看不到任何東西像html/template那樣。這是否意味着我必須使我的模板不可讀取,如下所示?

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}} 

回答

1

是,空白和線條直譯。如果你只有一行{{define}}或其他任何不產生輸出的行,那麼你的解析文件中會有一個空行。

理想情況下,因爲您正在使用模板,所以您不需要查看或編輯已解析的輸出。作爲參考,請使用JSP/JSF並查看它給您的醜陋輸出。在線查看大多數網頁的來源,他們也很難看。

祝你好運!

2

Whitespace在這種情況下,在用戶的瀏覽器中呈現的輸出沒有區別,所以控制它在高於或許美學上沒有多大意義。換句話說,可以有格式良好的模板(我更喜歡)或部分格式良好的HTML(不嵌套縮進)。使用任何現有格式化程序選擇一個或後處理HTML。

5

您可以使用空格控制器

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

自走'1.6' https://golang.org/doc/go1.6#template – webwurst

+0

是,1.6之前謝謝@webwurst,你可以檢查HTTPS ://golang.org/pkg/text/template/#hdr-Text_and_spaces – hkulekci

+0

這隻適用於'text/template',而不是'html/template'。 –