登录
首页 >  Golang >  Go教程

Go template 如何赋值变量?

时间:2024-12-17 20:52:03 240浏览 收藏

怎么入门Golang编程?需要学习哪些知识点?这是新手们刚接触编程时常见的问题;下面golang学习网就来给大家整理分享一些知识点,希望能够给初学者一些帮助。本篇文章就来介绍《Go template 如何赋值变量? 》,涉及到,有需要的可以收藏一下

Go template 如何赋值变量?

go template 如何赋值变量?

go 中通过变量赋值来填充模板内容,这与 php 的 assign 方法类似。

当执行模板时,通过 execute 函数的第二个参数传入变量。该参数可以是 map 或 struct,包含模板中使用的变量。

对于您的示例代码,可以如下方式赋值变量:

import (
    "text/template"
    "os"
)

type filename struct {
    name string
}

func main() {
    // 模板内容
    const templatetext = `
        
    {{range .filelist}}
  • {{.name}}
  • {{end}}
` // 数据 filelist := []filename{{"a.txt"}, {"b.txt"}} // 创建模板 t := template.must(template.new("tmpl").parse(templatetext)) // 赋值并执行模板 err := t.execute(os.stdout, map[string]interface{}{"filelist": filelist}) if err != nil { panic(err) } }

结果如下:

  • a.txt
  • b.txt

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>