首页 > 解决方案 > 无法使用 Go 的“文本/模板”库导入变量

问题描述

我有以下模板文件:

// main.tmpl
This is the main.                // line 1
{{ template "myFunc" }}          // line 2
{{- $name }}       // line 3
// helper.tmpl
This is a helper
{{- $name := "Nick" -}}

{{- define "myFunc" -}}
  Hello
{{- end -}}

围棋操场上;

package main

import (
  "text/template"
  "io/ioutil"
  "fmt"
  "bytes"

)

func main() {
    files := []string{"helper.tmpl", "main.tmpl"}
    t := template.New(files[0]).Funcs(make(map[string]interface{}))

    // Read the contents of each file, and parse it.
    // Couldn't get template.ParseFiles working, kept getting
    // "incomplete or empty template" errors.
    for _, file := range files {
        f, err := ioutil.ReadFile(file)
        if err != nil {
            fmt.Println(err.Error())
        }
        t.Parse(string(f))
        if err != nil {
            fmt.Println(err.Error())
        }
    }

    var buf bytes.Buffer
    err := t.Execute(&buf, make(map[string]string))
    if err != nil {
        fmt.Println(err.Error())
    }
    fmt.Println(buf.String())
}

当我运行我的主程序时,保持main.tmpl原样,输出是:

This is a helper.

但是,当我在删除第 3 行后运行 main 时main.tmpl,输出为:

This is the main.
Hello

问:为什么调用一个变量helper.tmpl会导致覆盖This is the main.,并忽略其余的执行main.tmpl?似乎缓冲区被覆盖了。这是一个错误吗?

提前致谢。

标签: gogo-templates

解决方案


https://golang.org/pkg/text/template/#hdr-Variables

变量的范围扩展到声明它的控制结构(“if”、“with”或“range”)的“结束”操作,如果没有这样的控制结构,则扩展到模板的末尾。模板调用不会从其调用点继承变量。


推荐阅读