duanlang1196 2017-07-25 17:07
浏览 139

使用Golang渲染模板时,无法读取其他文件夹中的CSS和图像

I am trying to render a template using the html/template module of Golang. But only CSS files and images from the same folder as the page i am rendering are executed, those located in a different folder are ignored. Here is my code:

func render(w http.ResponseWriter, filename string, data interface{}) {
    tmpl, err := template.ParseFiles(filename)
    if err != nil {
      http.Error(w, err.Error(), http.StatusInternalServerError)
    }
    if err := tmpl.Execute(w, data); err != nil {
      http.Error(w, err.Error(), http.StatusInternalServerError)
    }
  }

For this page for example:

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="description" content="">
  <meta name="author" content="">
  <title>Start Connect</title>
  <link href="../css/bootstrap.min.css" rel="stylesheet">
  <link href="one-page.css" rel="stylesheet">
</head>

The one-page.css is executed but not the bootstrap.

  • 写回答

1条回答 默认 最新

  • dongzi4030 2017-07-25 23:29
    关注

    Using ../css on the web should be avoided and likely is your error source. Your go server likely cannot resolve the file (because you don't have a handler for the ../css URI). So you should change the ../css part to /css and tell your server (you didn't provide details, so I cannot show you code) to handle /css URIs by serving the files.

    Assuming that you are using the default net/http mux, your code should look something like:

    mux := http.NewServeMux()
    mux.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir("css"))))
    http.ListenAndServe(":8080", mux)
    
    评论

报告相同问题?

悬赏问题

  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决