1 回答

TA貢獻1893條經驗 獲得超10個贊
package main
import (
"log"
"os"
"text/template"
)
func main() {
// Define a template.
const tmpl = `
echo &1
{{range $i,$a := .Command}}{{if gt $i 0 }} && {{end}}{{.}}{{end}}
echo 2
`
// Prepare some data
type App struct {
Data string
Command []string
}
data := App{"test data", []string{"app1", "app2", "app3"}}
// Create a new template and parse into it.
t := template.Must(template.New("tmpl").Parse(tmpl))
// Execute the template with data
err := t.Execute(os.Stdout, data)
if err != nil {
log.Println("executing template:", err)
}
}
游樂場示例
給出輸出
echo &1
app1 && app2 && app3
echo 2
Program exited.
如果從代碼中刪除了[]App,則還需要刪除range模板中使用的。
- 1 回答
- 0 關注
- 142 瀏覽
添加回答
舉報