惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

云风的 BLOG
云风的 BLOG
M
MIT News - Artificial intelligence
博客园 - Franky
J
Java Code Geeks
V
Visual Studio Blog
G
Google Developers Blog
罗磊的独立博客
MongoDB | Blog
MongoDB | Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Recent Announcements
Recent Announcements
Last Week in AI
Last Week in AI
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Stack Overflow Blog
Stack Overflow Blog
博客园 - 司徒正美
The GitHub Blog
The GitHub Blog
腾讯CDC
阮一峰的网络日志
阮一峰的网络日志
V
V2EX
博客园 - 【当耐特】
IT之家
IT之家
I
InfoQ
U
Unit 42
C
Check Point Blog
Martin Fowler
Martin Fowler

秋码分享

我是如何解决将 c++ 编译成可以在 node.js 中使用的 *.node,中间出现的一大堆问题的(指纹浏览器基石篇) eSIM Plus 爱沙尼亚手机号彻底翻车?“永久有效”悄然变成了一年! 接码平台 SMS-Activate 余额可以转移到新平台使用,截止日期:2026年1月29日 是时候将 hugo-theme-kiwi 主题提交到 themes.gohugo.io 站点上了 Flux2 刚开源就凉了?Z-Image 本地部署狠狠打了个样 声音的未来:Chatterbox —— 用「夸张度旋钮」提升表现力的开源 TTS 向导 还以为那只是换个背景?Qwen-Image-Edit 在 ComfyUI 中能做到更离谱的事 Windows 结合最新版 ComfyUI 部署阿里最新开源的 Qwen-Image 图像大模型 从零样本到跨场景:Seed-VC语音转换技术的革命性突破 大语音模型轻量化革命:MegaTTS3 如何重新定义文本生成语音的技术边界(windows篇) 竞赛级编程大模型OlympicCoder-7B之本地部署(Windows篇) 阿里开源了端到端全模态大模型Qwen-2.5-Omini-7B之本地部署(windows篇) 语音识别之whisper本地部署(实时语音之开篇) 甭管是个人还是企业都能部署的Mistral-Small3.1,远超同级别的模型 文生音乐开源项目DiffRhythm,8G显存本地部署之Windows篇 阿里QwQ-32B本地部署指南:用Ollama轻松运行320亿参数大模型 基于Qwen2.5大模型的Spark-TTS,零样本语音克隆,CPU可运行之本地部署(Windows篇) 智谱开源了文生图CogView4-6B模型,支持中文提示词之本地部署(Windows篇) 基于歌词生成整首歌的开源AI音乐模型,支持中、英、日、韩等多种语言,本地化部署YuE(windows篇) 阿里云开源的文生视频万相 Wan2.1之本地部署Wan2.1-T2V-1.3B模型 互动式开源AI图像编辑神器,Windows11本地部署 MagicQuill 本地部署Qwen2.5-VL-7B-Instruct多模态视觉大模型(Windows篇) 保持角色一致性的绘本生成AI开源项目之Story-Adapter本地部署Windows篇 本地部署 Stable Diffusion 3.5(最新 ComfyUI记录篇) 谁说Win7安装不了Node.js最新版的呢?都2025年,还不更新系统到Win11 vs code远程调试Linux服务器上的php代码 浏览器定制 | Windows11 编译 Chromium 133.0.6885.0(截稿前Chromium最新版之编译篇[一]) 不说是彻底搞懂,至少让你不再惧怕c/c++指针,以及各种奇葩指针变种 解决windows下php8.x及以上版本,在Apache2.4中无法加载CURL扩展的问题 在 Windows8.1 下编译 Chromium (103.0.5060.68 之三)
把握住golang中的template,方能驾驭得了Hugo主题的template
一个游离于山间之上的江湖漫行者。A jungle wanderer who wanders above the mountain · 2023-07-08 · via 秋码分享

不置可否,Hugotemplate同样是使用golang的标准库html/template。为了能实现一个属于自己独特的Hugo theme,或是修改他人的主题,都得对其模板语法有所知晓,方能改的称心如意,亦或是制作出一套即简约,又不失典雅的Hugo theme

创建golang项目

很明显的事,我们首先得先创建个golang项目,才能去讲解golang中的html/template,关于这一点,毋庸置疑。毕竟现在玩的是golang,说的是golang标准库html/template

好了,闲话少叙,切入正题。关于golang怎么创建项目,您应该是比较清楚的吧!否则的话,您是不会浏览这篇文章的,当然咯,也不能这样说的哦!或许他只是想了解下golang的模板语法,以便能够开发Hugo theme,这倒也是。

关于该如何配置golangmodule相关属性,可以查看以往的文章,本文将不再赘述,而是着重讲解html/template语法。

您在您电脑任意空文件下,在cmd(也就是命令行)中键入如下命令即可创建项目。

go mod init template.qiucode.cn #其中 template.qiucode.cn 是您项目模块名称,您可以起个响亮的名字,以便符合您的气质!(纯属笑谈)

在当前目录下新建main.go文件,并键入如下代码:

package main

import (
"log"
"net/http"
)

func main() {

	mux := http.NewServeMux()
	mux.HandleFunc("/", home)
	mux.HandleFunc("/blog/view", snippetView)
	mux.HandleFunc("/blog/create", snippetCreate)
	log.Print("Starting server on :4000")
	err := http.ListenAndServe(":4000", mux)
	log.Fatal(err)

}

我们将原先请求处理方法堆积在main.go文件中,抽离到新文件中。继而需新建handlers.go文件,至于内容便是如下:

package main

import (
	"fmt"
	"net/http"
	"strconv"
)

func home(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path != "/" {
		http.NotFound(w, r)
		return
	}
	w.Write([]byte("Hello from Snippetbox"))
}

func snippetView(w http.ResponseWriter, r *http.Request) {
	id, err := strconv.Atoi(r.URL.Query().Get("id"))
		if err != nil || id < 1 {
		http.NotFound(w, r)
		return
	}

	fmt.Fprintf(w, "Display a specific snippet with ID %d...", id)
}

func snippetCreate(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		w.Header().Set("Allow", http.MethodPost)
		http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
		return
	}
	w.Write([]byte("Create a new snippet..."))
}

模板组成

在当前文件夹创建home.tmpl模板文件,文件路径如下。

<!doctype html>
<html lang='zh'>
    <head>
        <meta charset='utf-8'>
        <title>首页</title>
    </head>
    <body>
        <header>
            <h1><a href='/'>这是头部</a></h1>
        </header>
        <main>
            <h2>主体部分s</h2>
            <p>写点什么吧!</p>
        </main>
        <footer>Powered by <a href='https://golang.org/'>Go</a></footer>
    </body>
</html>

回到handlers.go文件,修改其home处理函数。

package main

import (
	"fmt"
	"html/template" // 新添加
    "log"           // 新添加
	"net/http"
	"strconv"
)

func home(w http.ResponseWriter, r *http.Request) {

	if r.URL.Path != "/" {
		http.NotFound(w, r)
		return
	}
	
	//解析模板文件
	ts, err := template.ParseFiles("./ui/html/pages/home.tmpl")
	if err != nil {
		log.Print(err.Error())
		http.Error(w, "Internal Server Error", 500)
		return
	}
	
	err = ts.Execute(w, nil)
	if err != nil {
		log.Print(err.Error())
		http.Error(w, "Internal Server Error", 500)
	}
}

//... 省略其他方法

诚然,文件夹也会有更多的*.tmpl文件,该如何将头部、侧边栏、底部等公共内容共享给其他页面呢?为了剔除冗余内容,便是所有模板文件都将包含base.tmpl文件。

{{define "base"}}
<!doctype html>
<html lang='zh'>
    <head>
        <meta charset='utf-8'>
        <title>{{template "title" .}} - 秋码记录</title>
    </head>
    <body>
        <header>
            <h1><a href='/'>这是头部</a></h1>
        </header>
        <main>
            {{template "main" .}}
        </main>
        <footer>Powered by <a href='https://golang.org/'>Go</a></footer>
    </body>
</html>
{{end}}

{{define "base"}}...{{end}} 操作来定义一个模板名称为base,其中包含我们想要在每个页面上出现的内容。 在此内部,我们使用 {{template "title" .}} {{template "main" .}} 操作来 表示我们想要在特定的位置调用其他命名模板(称为 titlemain) 。

让我们修改下ui/html/pages/home.tmpl文件内容。

{{define "title"}}Home{{end}}
{{define "main"}}
    <h2>这是主体</h2>
    <p>说点什么吧!</p>
{{end}}

当然,我们还得去修改handlers.go中的home处理函数。

package main

import (
	"fmt"
	"html/template" // 新添加
    "log"           // 新添加
	"net/http"
	"strconv"
)

func home(w http.ResponseWriter, r *http.Request) {

	if r.URL.Path != "/" {
		http.NotFound(w, r)
		return
	}
	
	files := []string{
		"./ui/html/base.tmpl",
		"./ui/html/pages/home.tmpl",
	}
		
	ts, err := template.ParseFiles(files...)
	if err != nil {
		log.Print(err.Error())
		http.Error(w, "Internal Server Error", 500)
		return
	}

	
	err = ts.ExecuteTemplate(w, "base", nil)
	if err != nil {
		log.Print(err.Error())
		http.Error(w, "Internal Server Error", 500)
	}
		
}

//... 省略其他方法

所以现在,我们的模板集不再直接包含 HTML,而是包含 3 个命名模板 — basetitlemain。 我们使用ExecuteTemplate()方法告诉 Go, 我们具体 想要使用base的内容进行响应(这又调用我们的titlemain模板)。

模板嵌入

我们希望某些内容抽离出来,可以在不同页面或布局中重复使用。

为了说明这一点,让我们创建一个包含以下部分内容的导航栏。

{{define "nav"}}
    <nav>
        <a href='/'>首页</a>
    </nav>
{{end}}

同时,修改ui/html/base.tmpl文件。

{{define "base"}}
<!doctype html>
<html lang='zh'>
    <head>
        <meta charset='utf-8'>
        <title>{{template "title" .}} - 秋码记录</title>
    </head>
    <body>
        <header>
            <h1><a href='/'>这是头部</a></h1>
        </header>
        {{template "nav" .}}
        <main>
{{template "main" .}} {{/*添加了这一行内容*/}}
        </main>
        <footer>Powered by <a href='https://golang.org/'>Go</a></footer>
    </body>
</html>
{{end}}

当然,handlers.go文件中的home处理函数也得做相应修改。

package main

import (
	"fmt"
	"html/template" // 新添加
    "log"           // 新添加
	"net/http"
	"strconv"
)

func home(w http.ResponseWriter, r *http.Request) {

	if r.URL.Path != "/" {
		http.NotFound(w, r)
		return
	}
	
	files := []string{
		"./ui/html/base.tmpl",
        "./ui/html/partials/nav.tmpl", //添加这一行内容
		"./ui/html/pages/home.tmpl",
	}
		
	ts, err := template.ParseFiles(files...)
	if err != nil {
		log.Print(err.Error())
		http.Error(w, "Internal Server Error", 500)
		return
	}

	
	err = ts.ExecuteTemplate(w, "base", nil)
	if err != nil {
		log.Print(err.Error())
		http.Error(w, "Internal Server Error", 500)
	}
		
}

//... 省略其他方法

block

在上述您也看到了,使用的是{{template}}。其实,golang还会我们提供了另外,也就是Hugo·``中常用的{{block}} … {{end}}```操作。

例如:

{{define "base"}}
    <h1>An example template</h1>
    {{block "sidebar" .}}
    	<p>My default sidebar content</p>
    {{end}}
{{end}}

您不需要在 {{block}} 之间包含任何默认内容 和{{end}}操作。 在这种情况下,调用的模板就像是“可选的”。 如果模板 存在于模板集中,则将其渲染。 但如果不这样做,那就什么都不是 显示。