猿问

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

我在控制空白和仍然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 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. 这真的意味着我必须像下面这样使我的模板不可读吗?


布局.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}}


墨色风雨
浏览 330回答 3
3回答

手掌心

您可以使用空白控制器{{range .foos -}} // eats trailing whitespace&nbsp; &nbsp; <tr><td>do something</td></tr>{{- end}} // eats leading whitespace (\n from previous line)

慕运维8079593

在这种情况下,空白对用户浏览器的渲染输出没有影响,因此控制它在美学上没有多大意义。换句话说,您可以拥有格式良好的模板(我更喜欢)或部分格式良好的 HTML(无嵌套缩进)。选择一个或使用任何现有的格式化程序对 HTML 进行后处理。
随时随地看视频慕课网APP

相关分类

Go
我要回答