G01学习笔记-7

阅读位置9.7

知识点

1、mux.router 静态资源访问

 r.PathPrefix("/js/").Handler(http.FileServer(http.Dir("./public")))

PathPrefix() 匹配参数里 /css/ 前缀的 URI , 链式调用 Handler() 指定处理器为 http.FileServer()。

http.FileServer() 是文件目录处理器,参数 http.Dir(“./public”) 是指定在此目录下寻找文件

2、Go 标准库的模板分层

关键词 definetemplate

{{define ... }} 是定义模板,而 {{template ...}} 是使用模板。
{{define ... }} 跟着的参数是模板的名称,而 {{template ...}} 有两个参数,第一个是模板,第二个是传给模板使用的数据。

{{define "template_name"}}
{{template "template_name"  .}}

3、渲染模版

filepath : 路径处理包
filepath.Glob(): 生成与传参匹配的文件名称 Slice
template.ParseFiles(): 解析模板文件
Template.ExecuteTemplate(): 渲染模板

 files, err := filepath.Glob(dirPrefix + "/layouts/*.gohtml")

// 在 Slice 里新增我们的目标文件
newFiles := append(files, dirPrefix+"/articles/index.gohtml")

// 解析模板文件
tmpl, err := template.ParseFiles(newFiles...)

// 渲染模板,将所有文章的数据传输进去
tmpl.ExecuteTemplate(w, "app", articles)

作业

app/http/controllers/page_controller

// Home 首页
func (*PagesController) Home(w http.ResponseWriter, r *http.Request) {
    view.Render(w, view.D{},  "home")
}

// About 关于我们页面
func (*PagesController) About(w http.ResponseWriter, r *http.Request) {
    view.Render(w, view.D{},  "pages.about")
}

// NotFound 404 页面
func (*PagesController) NotFound(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusNotFound)
    view.Render(w, view.D{},  "not_found")
}

resource/views/pages/about.gohtml

{{define "title"}}
  关于我们
{{end}}

{{define "main"}}
  <div class="col-md-9 blog-main">
    <h1>欢迎来到goblog</h1>
    此博客是用以记录编程笔记,如您有反馈或建议,请联系
    <a href="mailto:zcold@example.com">zcold@example.com</a>
  </div>

{{end}}

G01学习笔记-7

本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!