dousuo8400 2014-08-01 18:30
浏览 57
已采纳

Golang无法查看外部软件包中的模板

I am attempting to write a reusable package in Go. I'm using a structure similar to that described here but slightly different:

/src/bitbucket.org/EXTERNAL_PROJECT_NAME/EXTERNAL_PACKAGE_NAME/...
/src/INTERNAL_PROJECT_NAME/INTERNAL_PACKAGE_NAME/...

Or should the second line be:

/src/bitbucket.org/INTERNAL_PROJECT_NAME/INTERNAL_PACKAGE_NAME/...

Everything works until I need to access a non-go file that exists in the external package. For example, I have some built in templates that I would like to be available without having to include them in my internal projects templates directory.

To that end, I have a "templates" directory in the external project where I want to house some built-in templates and a "templates" directory in my internal project where custom templates will go. But when I attempt to parse templates from the external project template directory, it can't find them.

So how would I go about indicating that I want to get the templates from the external package directory instead of the internal one? I could adjust the path to something like the following:

../../bitbucket.org/EXTERNAL_PROJECT_NAME/EXTERNAL_PACKAGE_NAME/templates/file.html

but this is obviously very clumsy and depends on individual setup, so that's not going to work. In general, if I want to reference a file in an external package instead of my internal project directory, how would I do this gracefully?

Thanks!

  • 写回答

2条回答 默认 最新

  • doulao7572 2014-08-04 13:58
    关注

    Turns out there is a pretty simple solution. Looks something like the following:

    package main
    
    import (
        "bitbucket.org/EXTERNAL_PROJECT/EXTERNAL_PACKAGE"
        "go/build"
    )
    
    func main() {
        SrcRoot := "/src"
        PackageDir := "/bitbucket.org/EXTERNAL_PROJECT/EXTERNAL_PACKAGE"
        InternalTemplateDir := build.Default.GOPATH + SrcRoot + PackageDir + "/templates/"
    }
    

    GOROOT here provides us with the path to the directory containing all our go code. From there, I want to reference the templates directory in the package source. With InternalTemplateDir, I now have the base path from which to reference templates within the external package.

    For ease of use, I will probably build a template loader that checks for a file on an internal file path first and then checks for the same file in the external package, so that any given template can be overridden by including it internally, but essential templates will all have built in versions as well.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大