dongzhuo6137 2013-03-04 19:14
浏览 59
已采纳

FuncMap的多个模板

The Goal: using multiple templates in an HTTP server where I want to change newlines into <br/> tags on some strings.

A stripped down example:

I have two templates a.tmpl and b.tmpl which look like this:

Template a {{dosomething}}

(and similar the other template). Both reside in a directory called templates. I believe that I need to create a function to do the -> <br /> replacement (dosomething above).

This is my (non working) sample code:

package main

import (
    "log"
    "text/template"
)

func main() {
    // funcMap := template.FuncMap{
    //  "dosomething": func() string { return "done something" },
    // }

    templates, err := template.ParseGlob("templates/*.tmpl")
    if err != nil {
        log.Fatal(err)
    }
    log.Printf("%#v", templates)

}

The error message is:

2013/03/04 20:08:19 template: a.tmpl:1: function "dosomething" not defined
exit status 1

which makes sense, because during the parsing time, the function dosomething is not known.

  1. How can I use my function in multiple templates? Is the answer to this question here on so the only way to go?
  2. Is this the correct approach? Remember, I'd like to change the text on some strings, similar to the title example in the documentation (http://golang.org/pkg/text/template/#FuncMap - Example (Func))?
  3. How do I access b.tmpl in the following code:

    package main
    
    import (
        "log"
        "text/template"
    )
    
    func main() {
        funcMap := template.FuncMap{
            "dosomething": func() string { return "done something" },
        }
    
        t, err := template.New("a.tmpl").Funcs(funcMap).ParseGlob("templates/*.tmpl")
        if err != nil {
            log.Fatal(err)
        }
        log.Printf("%#v", t)
    }
    
  • 写回答

1条回答 默认 最新

  • duanmiaosi0150 2013-03-04 20:59
    关注

    Your last snippet of code looks about right to me.

    To render b.tmpl, just call

    t.ExecuteTemplate(w, "b.tmpl", data)
    

    You can access a.tmpl the same way; I would recommend doing this for consistency, rather than setting the name to "a.tmpl" in the call to New.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题