亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 html/template 中的操作后控制空格?

如何在 html/template 中的操作后控制空格?

Go
墨色風雨 2021-06-04 18:51:46
我在控制空白和仍然html/template以可讀的方式格式化模板時遇到問題。我的模板看起來像這樣:布局.tmpl{{define "layout"}}<!DOCTYPE html><html>        <head>                <title>{{.title}}</title>        </head>        <body>                {{ template "body" . }}        </body></html>{{end}}正文.tmpl{{define "body"}}{{ range .items }}{{.count}} items are made of {{.material}}{{end}}{{end}}代碼package mainimport (    "os"    "text/template")type View struct {    layout string    body   string}type Smap map[string]stringfunc (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 angora3 items are made of wool    </body></html>我想要的是:<!DOCTYPE html><html>    <head>        <title>stock</title>    </head>    <body>2 items are made of angora3 items are made of wool    </body></html>在其他模板語言中,我可以這樣說[[- value -]]并且刪除了操作前后的空格,但我在html/template. 這真的意味著我必須像下面這樣使我的模板不可讀嗎?布局.tmpl{{define "layout"}}<!DOCTYPE html><html>    <head>        <title>.title</title>    </head>    <body>{{ template "body" . }} </body></html>{{end}}正文.tmpl{{define "body"}}{{ range .items }}{{.count}} items are made of {{.material}}{{end}}{{end}}
查看完整描述

3 回答

?
手掌心

TA貢獻1942條經驗 獲得超3個贊

您可以使用空白控制器


{{range .foos -}} // eats trailing whitespace

    <tr><td>do something</td></tr>

{{- end}} // eats leading whitespace (\n from previous line)


查看完整回答
反對 回復 2021-06-21
?
慕運維8079593

TA貢獻1876條經驗 獲得超5個贊

在這種情況下,空白對用戶瀏覽器的渲染輸出沒有影響,因此控制它在美學上沒有多大意義。

換句話說,您可以擁有格式良好的模板(我更喜歡)或部分格式良好的 HTML(無嵌套縮進)。選擇一個或使用任何現有的格式化程序對 HTML 進行后處理。


查看完整回答
反對 回復 2021-06-21
  • 3 回答
  • 0 關注
  • 338 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號