登录
首页 >  Golang >  Go问答

如何为模块在导入时设置别名?

来源:stackoverflow

时间:2024-02-08 09:27:27 342浏览 收藏

珍惜时间,勤奋学习!今天给大家带来《如何为模块在导入时设置别名?》,正文内容主要涉及到等等,如果你正在学习Golang,或者是对Golang有疑问,欢迎大家关注我!后面我会持续更新相关内容的,希望都能帮到正在学习的大家!

问题内容

手册给出了一个例子:

t := &template{
    templates: template.must(template.parseglob("public/views/*.html")),
}

其中模板沿着 public/views/*.html 路径编译。

我需要更改此代码,以便模板不是在一个路径中编译,而是在两个指定路径中编译,即 pjt_*/templates/include/*.htmlpjt_*/templates/site/*.html

我的代码:

package main

import(
"html/template"
"io"
"net/http"

"github.com/labstack/echo/v4"
)

type TemplateRenderer struct {
templates *template.Template
}

func (t *TemplateRenderer) Render(w io.Writer, name string, data interface{}, c echo.Context) error {

if viewContext, isMap := data.(map[string]interface{}); isMap {
viewContext["reverse"] = c.Echo().Reverse
}

return t.templates.ExecuteTemplate(w, name, data)
}

func main() {
  e := echo.New()
  e.Renderer = &TemplateRenderer{
      // here I want templates to be compiled, not only for
      // "pjt_*/templates/include/*.html" but also "pjt_*/templates/site/*.html"
      templates: template.Must(template.ParseGlob("pjt_*/templates/include/*.html")),
  }

  e.GET("/something", func(c echo.Context) error {
      return c.Render(http.StatusOK, "template.html", "World")
  })

  e.Logger.Fatal(e.Start(":8000"))
}

ps 指南,以防万一:https://echo.labstack.com/guide/templates/


正确答案


template.ParseGlob 采用模式并从该模式标识的文件中解析模板定义。

使用与 pjt_*/templates/include/*.htmlpjt_*/templates/site/*.html 都匹配的模式来调用它。

今天关于《如何为模块在导入时设置别名?》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

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