登录
首页 >  Golang >  Go问答

无法使用 Go 的“文本/模板”库导入变量

来源:stackoverflow

时间:2024-03-30 12:03:34 357浏览 收藏

偷偷努力,悄无声息地变强,然后惊艳所有人!哈哈,小伙伴们又来学习啦~今天我将给大家介绍《无法使用 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 -}}

go 演示;

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 时,保持 main.tmpl 不变,输出为:

this is a helper.

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

This is the main.
Hello

问:为什么从 helper.tmpl 调用变量会导致覆盖 this is the main.,并且执行时忽略 main.tmpl 的其余部分?看起来缓冲区几乎被覆盖了。这是一个错误吗?

提前致谢。


解决方案


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

变量的作用域延伸至控件的“结束”操作 声明它的结构(“if”、“with”或“range”),或者 如果没有这样的控制结构,则为模板末尾。 A 模板调用不会从其所在点继承变量 调用。

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《无法使用 Go 的“文本/模板”库导入变量》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>