按先后顺序,记录本站点的不断完善之旅。
1 - 站点搭建方法
主要涉及到hugo和docsy主题的使用。
hugo介绍
hugo是spf13的开源作品,目前任职于google,对他最早的印象是使用他的vim-spf13配置,后来又接触到他的cobra、plfag、viper... 为golang的生态完善做了很大贡献,致敬!
书归正传,hugo是基于golang开发的世界上最快的网站构建框架,本文介绍如何基于它构建技术类文档库,也可作为内部wiki或开源书籍使用。之所以没选择gitbook,发现CLI版本已于2018年停止维护了。
准备环境
安装git和hugo
-
具体过程此处不表。注意是安装hugo_extended的版本。
-
如果要编译成html,部署到webserver上,还需要安装nodejs 12+。
主题选择
选用Docsy主题,出自google的开源主题,很多流行项目使用此主题作为官方站点,有k8s、kubeflow、grpc、etcd、Selenium等,详见此。主要功能包含:
- 支持树形目录
- 国际化
- 搜索功能
- 移动端自适应适配
- 标签分类
- 全站打印
- 文档版本化
- 用户反馈等
官方提供了快速上手的脚手架,具体操作如下:
git clone https://github.com/google/docsy-example.git
脚手架初始化
cd docsy-example && git submodule update --init --recursive
本地启动,默认可通过localhost:1313
访问,官方提供了在线的预览地址。
hugo server
目录结构说明
默认脚手架目录结构如下,只关注config.toml
文件和content
目录,就可以满足日常使用。
➜ docsy-example git:(master) tree -L 1
.
├── assets # 静态资源
├── config.toml # 站点的配置文件:主题选择、名称、链接、页面分析、markdown解析引擎...
├── content # 站点内容:顶层导航,左侧树形章节
├── CONTRIBUTING.md
├── deploy.sh
├── docker-compose.yaml
├── Dockerfile
├── layouts # 可覆盖主题的默认布局,添加自定义页面布局
├── LICENSE
├── netlify.toml
├── package.json
├── README.md
├── resources
└── themes # Docsy主题的目录,hugo推荐的存放路径
重点说明
-
修改主题的页面布局
- 大部分内容可以通过修改根目录的config.toml的文件来实现
- 不能通过上条实现的,也不建议直接修改themes目录下的内容,copy到在根目录同样的相对路径上再修改,会覆盖默认主题相关的实现。
-
docsy主题默认提供了3种版面布局, 分别在content目录下,写markdown文件,不同目录按照各自类型风格渲染。
- docs技术文档类的布局
- blog博客类的布局
- community社区相关介绍的布局
-
docs的目录章节可以任意分级,目录下的_index.md或者_index.html为该章、节的首页描述。
-
根目录运行如下命令可编译最终html,可能会提示
POSTCSS
编译失败,需要根目录运行npm install
安装依赖。rm -rf public/ && HUGO_ENV="production" hugo --gc || exit 1
-
站点内搜索功能依赖编译后的json文件,需要上一步才能使用。
-
关于config.toml配置的解读(最新注释说明,可查看本站的原件)。
# 站点的访问地址,本地预览时(hugo server)可忽悠 baseURL = "https://xiaoping378.github.io" # 站点title,会被多语言里的设置覆盖 # title = "小平栈" # 是否生成robots文件 enableRobotsTXT = true # 主题选择,支持组合,优先级从左到右. theme = ["docsy"] # 页面上提供类似"最后修改"的信息 enableGitInfo = true # 国际化相关设置 # 默认语言的的站点内容路径 contentDir = "content" # 默认语言 defaultContentLanguage = "zh-cn" # 国际化翻译中,如果有缺失是否用占位符显示 enableMissingTranslationPlaceholders = true # 注释后,可以开启标签分类功能 # disableKinds = ["taxonomy", "taxonomyTerm"] [params.taxonomy] # set taxonomyCloud = [] to hide taxonomy clouds taxonomyCloud = ["tags"] # If used, must have same lang as taxonomyCloud taxonomyCloudTitle = ["标签"] # set taxonomyPageHeader = [] to hide taxonomies on the page headers taxonomyPageHeader = ["tags"] # 代码块高亮配置 pygmentsCodeFences = true pygmentsUseClasses = false # Use the new Chroma Go highlighter in Hugo. pygmentsUseClassic = false #pygmentsOptions = "linenos=table" # See https://help.farbox.com/pygments.html pygmentsStyle = "emacs" # 配置blog编译产物的路径. [permalinks] blog = "/:section/:year/:month/:day/:slug/" # markdown渲染引擎配置: https://github.com/russross/blackfriday # [blackfriday] # plainIDAnchors = true # hrefTargetBlank = true # angledQuotes = false # latexDashes = true # 图片引擎处理: https://github.com/disintegration/imaging [imaging] resampleFilter = "CatmullRom" quality = 75 anchor = "smart" # [services] # [services.googleAnalytics] # # Comment out the next line to disable GA tracking. Also disables the feature described in [params.ui.feedback]. # id = "UA-00000000-0" # Language configuration [languages] [languages.zh-cn] title = "现代技能栈" description = "小平-所思所为" languageName = "中文" # 用于多语言排序,越小越靠上。 weight = 1 # markdown的解析设置,抄的k8s 文档设置... [markup] [markup.goldmark] [markup.goldmark.extensions] definitionList = true table = true typographer = false [markup.goldmark.parser] attribute = true autoHeadingID = true autoHeadingIDType = "blackfriday" [markup.goldmark.renderer] unsafe = true [markup.highlight] codeFences = true guessSyntax = false hl_Lines = "" lineNoStart = 1 lineNos = false lineNumbersInTable = true noClasses = true style = "emacs" tabWidth = 4 [markup.tableOfContents] endLevel = 3 ordered = false startLevel = 2 # Everything below this are Site Params # Comment out if you don't want the "print entire section" link enabled. [outputs] section = ["HTML", "print", "RSS"] [params] copyright = "xiaoping378" privacy_policy = "#" # First one is picked as the Twitter card image if not set on page. # images = ["images/project-illustration.png"] # Menu title if your navbar has a versions selector to access old versions of your site. # This menu appears only if you have at least one [params.versions] set. version_menu = "Releases" # Flag used in the "version-banner" partial to decide whether to display a # banner on every page indicating that this is an archived version of the docs. # Set this flag to "true" if you want to display the banner. archived_version = false # The version number for the version of the docs represented in this doc set. # Used in the "version-banner" partial to display a version number for the # current doc set. version = "0.0" # A link to latest version of the docs. Used in the "version-banner" partial to # point people to the main doc site. # url_latest_version = "https://example.com" # 方便用户反馈,提交技术文章问题的仓库地址 github_repo = "https://github.com/xiaoping378/xiaoping378.github.io" # 技术站点背后的项目issue地址 # github_project_repo = "https://github.com/xiaoping378/xiaoping378.github.io" # 以下三个是设置远程文档位置的,目前用不上,这里hack一下,不然“编辑此页”的功能会去链接到content/zh-cn下 # Specify a value here if your content directory is not in your repo's root directory github_subdir = "/" # Uncomment this if you have a newer GitHub repo with "main" as the default branch, # or specify a new value if you want to reference another branch in your GitHub links # github_branch= "main" # 支持三种搜索,三选一,禁用google搜索,需要注释掉此处 # gcs_engine_id = "d72aa9b2712488cc3" # Enable Algolia DocSearch algolia_docsearch = false # Enable Lunr.js offline search offlineSearch = false # 默认使用的Chroma代码高亮方案,可换成prism方案。 prism_syntax_highlighting = false # User interface configuration [params.ui] # 是否禁用面包屑导航. breadcrumb_disable = false # 是否禁用底部About链接 footer_about_disable = true # 是否展示项目logo,位置必须放置在 assets/icons/logo.svg navbar_logo = true # 在首页,上下滑动页面,顶部导航是否禁用半透明 navbar_translucent_over_cover_disable = false # 左侧章节树形目录默认是否处于折叠状态 sidebar_menu_compact = true # 左侧章节树形目录上是否不显示搜索框,前提是需要开启搜索功能 sidebar_search_disable = false # 关闭了google分析,下面功能不会启用 [params.ui.feedback] enable = true # The responses that the user sees after clicking "yes" (the page was helpful) or "no" (the page was not helpful). yes = 'Glad to hear it! Please <a href="https://github.com/USERNAME/REPOSITORY/issues/new">tell us how we can improve</a>.' no = 'Sorry to hear that. Please <a href="https://github.com/USERNAME/REPOSITORY/issues/new">tell us how we can improve</a>.' # 在文章上面显示“阅读时长:x分钟” [params.ui.readingtime] enable = false # 社区community版面要用到的参数 [params.links] # End user relevant links. These will show up on left side of footer and in the community page if you have one. [[params.links.user]] name = "个人邮箱 xiaoping378@163.com" url = "mailto:xiaoping378@163.com" icon = "fa fa-envelope" desc = "欢迎邮件交流" [[params.links.user]] name ="微博" url = "https://weibo.com/xiaoping378" icon = "fab fa-weibo" desc = "个人微博,基本不用" [[params.links.user]] name = "知乎" url = "https://www.zhihu.com/people/xiaoping378" icon = "fab fa-zhihu" desc = "知乎专栏" # Developer relevant links. These will show up on right side of footer and in the community page if you have one. [[params.links.developer]] name = "GitHub" url = "https://github.com/xiaoping378/xiaoping378.github.io" icon = "fab fa-github" desc = "文集开源地址!" [[params.links.developer]] name = "Slack" url = "https://example.org/slack" icon = "fab fa-slack" desc = "未开通" [[params.links.developer]] name = "Developer mailing list" url = "https://example.org/mail" icon = "fa fa-envelope" desc = "未开通"
总结
不定期更新此文,待进一步优化,,,
如果自己搭建嫌麻烦,可直接Copy本站,编写自己的内容即可,搭建本站时,也遇到了Docsy国际化方面的问题,已提交官方PR修复。
下文介绍使用github的actions和pages自动托管站点。
2 - 自动托管markdown
利用github actions和pages实现自动更新托管内容,本站点已实现commit md后,自动更新码云page和Github page页面。
项目仓库的名字由来
本源码仓之所以起如此长的名字,完全是因为github pages的不成熟,不然会带个小尾巴:
如果叫 blog, github的托管页面的访问地址会是 xiaoping378.github.io/blog,这也没什么,但会和hugo的static机制出现冲突。
3 - 编写文章注意项
本章节主要描述日常编写文章的注意事项和docsy主题内的使用技巧。
编写markdown
图片路径问题
习惯md文件中的图片路径写成![](/images/file.png)
,但hugo中图片实际要存放到/static/images/
路径下,hugo会自动渲染到站点的根路径/
上。
这样的话,无法在编辑器中预览md了,有两种玩法如下:
- 可以使用一个临时目录,把图片和md文件放到同一目录,编写完毕后,再把图片和md文件放置上述合适的目录位置上。
- 日常一直启用
hugo server
编写文章,放弃编辑器中预览md,后面还会有别的坑....
推荐后者,本人日常使用VSCode编写md,和代码开发同款,这里推荐安装mushan.vscode-paste-image
扩展,再额外如下配置:
"pasteImage.namePrefix": "${currentFileNameWithoutExt}-",
"pasteImage.path": "${projectRoot}/static/images/",
"pasteImage.basePath": "${projectRoot}",
"pasteImage.insertPattern": "${imageSyntaxPrefix}/images/${imageFileName}${imageSyntaxSuffix}"
日常编写文章,Alt+A
截图,Ctrl+Alt+A
粘贴到md文件,和hugo的配合,完美...
SEO优化关注点
日常文章编写,如下部分要精准描述,Google搜索引擎推荐使用description
的meta标签告诉它页面内容的,Docsy主题会自动把红框部分填充到layouts/partials/head.html
中。
hugo解析编译后,html页面会如下呈现:
日常编写注意事项
md文件中相互引用内容的路径要记得对应到站点html的路径上
比如此处引用自动托管markdown
文章,按照md习惯写,虽然编辑器上可以正常打开,但hugo渲染后的页面是404的。
[引用](./actions_pages.md)
需要改成[引用](../actions_pages)
[引用](/content/docs/1-site/actions_pages.md)
需要改成[引用](/docs/1-site/actions_pages)
不定时更新注意事项。日常编写,建议本机启用hugo server
实时预览,
文章weight的使用
文章开头的weight
部分决定了目录中的排序,推荐新开的系列文章,从两位数开始递增,比如30
, 以后老系列有更新的时候,免去批量修改调整排序的麻烦。
4 - markdown语法
This is a placeholder page. Replace it with your own content.
Text can be bold, italic, or strikethrough. Links should be blue with no underlines (unless hovered over).
There should be whitespace between paragraphs. Vape migas chillwave sriracha poutine try-hard distillery. Tattooed shabby chic small batch, pabst art party heirloom letterpress air plant pop-up. Sustainable chia skateboard art party banjo cardigan normcore affogato vexillologist quinoa meggings man bun master cleanse shoreditch readymade. Yuccie prism four dollar toast tbh cardigan iPhone, tumblr listicle live-edge VHS. Pug lyft normcore hot chicken biodiesel, actually keffiyeh thundercats photo booth pour-over twee fam food truck microdosing banh mi. Vice activated charcoal raclette unicorn live-edge post-ironic. Heirloom vexillologist coloring book, beard deep v letterpress echo park humblebrag tilde.
90's four loko seitan photo booth gochujang freegan tumeric listicle fam ugh humblebrag. Bespoke leggings gastropub, biodiesel brunch pug fashion axe meh swag art party neutra deep v chia. Enamel pin fanny pack knausgaard tofu, artisan cronut hammock meditation occupy master cleanse chartreuse lumbersexual. Kombucha kogi viral truffaut synth distillery single-origin coffee ugh slow-carb marfa selfies. Pitchfork schlitz semiotics fanny pack, ugh artisan vegan vaporware hexagon. Polaroid fixie post-ironic venmo wolf ramps kale chips.
There should be no margin above this first sentence.
Blockquotes should be a lighter gray with a border along the left side in the secondary color.
There should be no margin below this final sentence.
First Header 2
This is a normal paragraph following a header. Knausgaard kale chips snackwave microdosing cronut copper mug swag synth bitters letterpress glossier craft beer. Mumblecore bushwick authentic gochujang vegan chambray meditation jean shorts irony. Viral farm-to-table kale chips, pork belly palo santo distillery activated charcoal aesthetic jianbing air plant woke lomo VHS organic. Tattooed locavore succulents heirloom, small batch sriracha echo park DIY af. Shaman you probably haven't heard of them copper mug, crucifix green juice vape single-origin coffee brunch actually. Mustache etsy vexillologist raclette authentic fam. Tousled beard humblebrag asymmetrical. I love turkey, I love my job, I love my friends, I love Chardonnay!
Deae legum paulatimque terra, non vos mutata tacet: dic. Vocant docuique me plumas fila quin afuerunt copia haec o neque.
On big screens, paragraphs and headings should not take up the full container width, but we want tables, code blocks and similar to take the full width.
Scenester tumeric pickled, authentic crucifix post-ironic fam freegan VHS pork belly 8-bit yuccie PBR&B. I love this life we live in.
Second Header 2
This is a blockquote following a header. Bacon ipsum dolor sit amet t-bone doner shank drumstick, pork belly porchetta chuck sausage brisket ham hock rump pig. Chuck kielbasa leberkas, pork bresaola ham hock filet mignon cow shoulder short ribs biltong.
Header 3
This is a code block following a header.
Next level leggings before they sold out, PBR&B church-key shaman echo park. Kale chips occupy godard whatever pop-up freegan pork belly selfies. Gastropub Belinda subway tile woke post-ironic seitan. Shabby chic man bun semiotics vape, chia messenger bag plaid cardigan.
Header 4
- This is an unordered list following a header.
- This is an unordered list following a header.
- This is an unordered list following a header.
Header 5
- This is an ordered list following a header.
- This is an ordered list following a header.
- This is an ordered list following a header.
Header 6
What | Follows |
---|---|
A table | A header |
A table | A header |
A table | A header |
There's a horizontal rule above and below this.
Here is an unordered list:
- Liverpool F.C.
- Chelsea F.C.
- Manchester United F.C.
And an ordered list:
- Michael Brecker
- Seamus Blake
- Branford Marsalis
And an unordered task list:
- Create a Hugo theme
- Add task lists to it
- Take a vacation
And a "mixed" task list:
- Pack bags
- ?
- Travel!
And a nested list:
- Jackson 5
- Michael
- Tito
- Jackie
- Marlon
- Jermaine
- TMNT
- Leonardo
- Michelangelo
- Donatello
- Raphael
Definition lists can be used with Markdown syntax. Definition headers are bold.
- Name
- Godzilla
- Born
- 1952
- Birthplace
- Japan
- Color
- Green
Tables should have bold headings and alternating shaded rows.
Artist | Album | Year |
---|---|---|
Michael Jackson | Thriller | 1982 |
Prince | Purple Rain | 1984 |
Beastie Boys | License to Ill | 1986 |
If a table is too wide, it should scroll horizontally.
Artist | Album | Year | Label | Awards | Songs |
---|---|---|---|---|---|
Michael Jackson | Thriller | 1982 | Epic Records | Grammy Award for Album of the Year, American Music Award for Favorite Pop/Rock Album, American Music Award for Favorite Soul/R&B Album, Brit Award for Best Selling Album, Grammy Award for Best Engineered Album, Non-Classical | Wanna Be Startin' Somethin', Baby Be Mine, The Girl Is Mine, Thriller, Beat It, Billie Jean, Human Nature, P.Y.T. (Pretty Young Thing), The Lady in My Life |
Prince | Purple Rain | 1984 | Warner Brothers Records | Grammy Award for Best Score Soundtrack for Visual Media, American Music Award for Favorite Pop/Rock Album, American Music Award for Favorite Soul/R&B Album, Brit Award for Best Soundtrack/Cast Recording, Grammy Award for Best Rock Performance by a Duo or Group with Vocal | Let's Go Crazy, Take Me With U, The Beautiful Ones, Computer Blue, Darling Nikki, When Doves Cry, I Would Die 4 U, Baby I'm a Star, Purple Rain |
Beastie Boys | License to Ill | 1986 | Mercury Records | noawardsbutthistablecelliswide | Rhymin & Stealin, The New Style, She's Crafty, Posse in Effect, Slow Ride, Girls, (You Gotta) Fight for Your Right, No Sleep Till Brooklyn, Paul Revere, Hold It Now, Hit It, Brass Monkey, Slow and Low, Time to Get Ill |
Code snippets like var foo = "bar";
can be shown inline.
Also, this should vertically align
with this
and this.
Code can also be shown in a block element.
foo := "bar";
bar := "foo";
Code can also use syntax highlighting.
func main() {
input := `var foo = "bar";`
lexer := lexers.Get("javascript")
iterator, _ := lexer.Tokenise(nil, input)
style := styles.Get("github")
formatter := html.New(html.WithLineNumbers())
var buff bytes.Buffer
formatter.Format(&buff, style, iterator)
fmt.Println(buff.String())
}
Long, single-line code blocks should not wrap. They should horizontally scroll if they are too long. This line should be long enough to demonstrate this.
Inline code inside table cells should still be distinguishable.
Language | Code |
---|---|
Javascript | var foo = "bar"; |
Ruby | foo = "bar"{ |
Small images should be shown at their actual size.
Large images should always scale down and fit in the content container.
The photo above of the Spruce Picea abies shoot with foliage buds: Bjørn Erik Pedersen, CC-BY-SA.
Components
Alerts
Note
This is an alert with a title.Note
This is an alert with a title and Markdown.Warning
This is a warning with a title.Another Heading
Add some sections here to see how the ToC looks like. Bacon ipsum dolor sit amet t-bone doner shank drumstick, pork belly porchetta chuck sausage brisket ham hock rump pig. Chuck kielbasa leberkas, pork bresaola ham hock filet mignon cow shoulder short ribs biltong.
This Document
Inguina genus: Anaphen post: lingua violente voce suae meus aetate diversi. Orbis unam nec flammaeque status deam Silenum erat et a ferrea. Excitus rigidum ait: vestro et Herculis convicia: nitidae deseruit coniuge Proteaque adiciam eripitur? Sitim noceat signa probat quidem. Sua longis fugatis quidem genae.
Pixel Count
Tilde photo booth wayfarers cliche lomo intelligentsia man braid kombucha vaporware farm-to-table mixtape portland. PBR&B pickled cornhole ugh try-hard ethical subway tile. Fixie paleo intelligentsia pabst. Ennui waistcoat vinyl gochujang. Poutine salvia authentic affogato, chambray lumbersexual shabby chic.
Contact Info
Plaid hell of cred microdosing, succulents tilde pour-over. Offal shabby chic 3 wolf moon blue bottle raw denim normcore poutine pork belly.
External Links
Stumptown PBR&B keytar plaid street art, forage XOXO pitchfork selvage affogato green juice listicle pickled everyday carry hashtag. Organic sustainable letterpress sartorial scenester intelligentsia swag bushwick. Put a bird on it stumptown neutra locavore. IPhone typewriter messenger bag narwhal. Ennui cold-pressed seitan flannel keytar, single-origin coffee adaptogen occupy yuccie williamsburg chillwave shoreditch forage waistcoat.
This is the final element on the page and there should be no margin below this.