Golang无法执行ExecuteTemplate。

huangapple go评论77阅读模式
英文:

Golang can't ExecuteTemplate

问题

我需要执行ExecuteTemplate(文本和HTML)。我有以下代码片段:

import "text/template"
...

test_path := "/cnaize/home/test.txt"
testTmpl := template.New(test_path)
var test bytes.Buffer
if err := testTmpl.ExecuteTemplate(&test, test_path, mm.Args); err != nil {
    return err
}

但是在ExecuteTemplate中我遇到了invalid memory address or nil pointer dereference错误。当我将第一行改为import "html/template"时,我遇到了"/cnaize/home/test.txt" is an incomplete template错误。
我的test.txt文件内容如下:

Test

可能出了什么问题?

编辑:
我知道有关文档的内容,但我在https://github.com/arkxu/gomail/blob/master/message.go中找到了这个解决方案,这正是我所需要的,因为我不知道如何在template.ParseFiles()中设置args。使用文件夹名称的template.New()是可以的。而我的mm.Argsmap[message:Hello there!],我已经检查过了。

英文:

I need to ExecuteTemplate (text and html). I have next snippet:

import ("text/template")
...

test_path := "/cnaize/home/test.txt"
testTmpl := template.New(test_path)
var test bytes.Buffer
if err := testTmpl.ExecuteTemplate(&test, test_path, mm.Args); err != nil {
	return err
}

but I have error invalid memory address or nil pointer dereference in ExecuteTemplate. When I change first line to import ("html/template"), I have "/cnaize/home/test.txt" is an incomplete template error.
My test.txt:

Test

Where may be a problem?

EDITED:
I know about documentation, but I found this solution in https://github.com/arkxu/gomail/blob/master/message.go and it's exactly what I need, because I don't know how to set args in template.ParseFiles(). template.New() with folder name is ok. And my mm.Args is map[message:Hello there!], I've checked it.

答案1

得分: 3

这里有两个问题:

  1. template.New() 用给定的名称初始化一个空模板,你给了一个路径,这是可以的,但可能不是你想要的。在使用库之前,请先阅读文档
    你可能要使用的是:template.ParseFiles()

  2. mm.Args 是什么?仅从代码片段和错误信息来看,我猜测 mm 是空的(nil)。

英文:

There are two things wrong here:

  1. template.New() initializes an empty template with the given name, you are giving a path, which is ok, but it probably is not what you want. Please read the documentation before using libraries naively.
    You are probably looking for: template.ParseFiles()

  2. what is mm.Args? From that snippet alone and the error I would guess mm is nil.

huangapple
  • 本文由 发表于 2014年7月15日 18:24:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/24755762.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定