diff --git a/.gitignore b/.gitignore index 13463b0..35ed95e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ # Hugo default output directory -/public +public +resources ## OS Files # Windows diff --git a/README.md b/README.md index f7d5f3f..bed3370 100644 --- a/README.md +++ b/README.md @@ -1,40 +1,53 @@ -# LoveIt Hugo Theme +# LoveIt Theme | Hugo -LoveIt is a clean, elegant, simple but not simpler blog theme for Hugo based on the original [LeaveIt Theme](https://github.com/liuzc/LeaveIt/) and [KeepIt Theme](https://github.com/liuzc/LeaveIt/) developed by [Dillon](https://dillonzq.com). +[中文 README](README.zh.md) -![hugo-theme-LoveIt](https://github.com/dillonzq/LoveIt/blob/master/images/screenshot.png) +**LoveIt** is a **clean**, **elegant** but **advanced** blog theme for [Hugo](https://gohugo.io/). + +It is based on the original [LeaveIt Theme](https://github.com/liuzc/LeaveIt/) and [KeepIt Theme](https://github.com/liuzc/LeaveIt/). + +![Hugo Theme LoveIt](exampleSite/static/images/Apple-Devices-Preview.png) ## Demo -To see this theme in action, Here is a live [demo site](https://suspicious-archimedes-ab369d.netlify.com) which is rendered with this theme. +To see this theme in action, here is a live [demo site](https://hugo-loveit-en.netlify.com) which is rendered with **LoveIt** theme. -People that are using **LoveIt**: +Websites using **LoveIt** theme: * [Dillon](https://dillonzq.com) +* Yours ## Features -* Optimized for performance: 99/100 on mobile and 100/100 on desktop in Google PageSpeed Insights +* Optimized for performance: 99/100 on mobile and 100/100 on desktop in [Google PageSpeed Insights](https://developers.google.com/speed/pagespeed/insights) +* Desktop / Mobile layouts support +* Dark / Light mode * Optimized SEO performance with a correct SEO SCHEMA based on JSON-LD * A More coerent style beetwen page and sections -* Multilanguage support +* Multilanguage support and I18N ready * Pagination support -* Google Analytics support -* Disqus Comment System -* Gitalk Comment System -* Valine Comment System -* Gravatar Support -* Local Avatar Support +* [Google Analytics](https://analytics.google.com/analytics) support +* Disqus comment system support by [Disqus](https://disqus.com) +* Gitalk comment system support by [Gitalk](https://github.com/gitalk/gitalk) +* Valine comment system support by [Valine](https://valine.js.org/) +* Gravatar support by [Gravatar](https://gravatar.com) +* Local Avatar support +* Up to 54 social sites supported * Share post support * Search engine verification support (Google, Bind, Yandex and Baidu) -* Added configuration file for use on [Netlify](https://www.netlify.com) -* Dark/Light mode -* Up to 54 social sites supported out-of-the-box [see the list here](https://github.com/Fastbyte01/KeepIt/wiki/List-of-social-platforms-supported-out-of-box) -* Translation ready -* Wrap Image with Figure Tag without Shortcode. Thanks [Junian.Net](https://www.junian.net/hugo-image-figure-wrap/) -* Load images with Lazy Load By [lazysizes](https://github.com/aFarkas/lazysizes) -* Automatically highlighting code By [Google code-prettify](https://github.com/google/code-prettify), Customizable styles via CSS. See the [themes gallery](https://rawgit.com/google/code-prettify/master/styles/index.html). -* Automagical image gallery with [lightGallery](https://github.com/sachinchoolur/lightGallery) +* Automatically converted images with Lazy Load by [lazysizes](https://github.com/aFarkas/lazysizes) +* Automatically highlighting code by chroma in Hugo +* Extended markdown syntax for [Font Awesome](https://fontawesome.com/) icons +* Math formula support by [Katex](https://katex.org/) +* Diagram syntax shortcode support by [mermaid](https://github.com/knsv/mermaid) +* Embedded music player support by [APlayer](https://github.com/MoePlayer/APlayer) and [MetingJS](https://github.com/metowolf/MetingJS) +* Bilibili player support +* Kinds of admonitions shortcode support +* Custom align and float style shortcodes support +* Animated typing support by [TypeIt](https://typeitjs.com/) +* Animated coutdown support by [jQuery.countdown](https://github.com/hilios/jQuery.countdown) +* Dynamic to top support by [Smooth Scroll](https://github.com/cferdinandi/smooth-scroll) +* CDN support * ... ## Getting Started @@ -46,7 +59,13 @@ Clone this repository to your hugo theme directory. git clone https://github.com/dillonzq/LoveIt.git ``` -Next, open config.toml in the base of the Hugo site and ensure the theme option is set to KeepIt: +Or, make this repository a submodule of your site directory. + +```bash + git submodule add https://github.com/dillonzq/LoveIt.git themes/LoveIt +``` + +Next, open `config.toml` in the base of the Hugo site and ensure the theme option is set to KeepIt: ```bash theme = "LoveIt" @@ -58,24 +77,25 @@ For more information read the [official setup guide](https://gohugo.io/documenta Take a look in the `exampleSite` folder. -This directory contains an example config file and the content for the demo. It serves as an example setup for your documentation. +This directory contains an example config file and the content for the demo for `en` and `zh` languages. +It serves as an example setup for your website. -Copy the `config.toml` in the root directory of your website. Overwrite the existing config file if necessary. +Copy the `config.toml` to the root directory of your website. Overwrite the existing config file if necessary. ## Content Suggestions A few suggestions to help you get a good looking site quickly: -* Keep blog posts in the content/posts directory, for example: content/posts/my-first-post.md -* Keep static pages in the content directory, for example: content/about.md -* Keep media like images in the static directory, for example: static/images/2019/10/screenshot.png +* Keep blog posts in the `content/posts` directory, for example: `content/posts/my-first-post.md` +* Keep static pages in the `content` directory, for example: `content/about.md` +* Keep media like images in the `static` directory, for example: `static/images/2019/9/screenshot.png` ## Customizing styles for your website If you want to change some styling to fit your own website needs, you can edit them: -* `assets/css/_varibales/default.scss`: You can override the variables in `_variables.scss` to customize the style -* `assets/css/_custom.scss` : You can put your custom css in this file +* `assets/css/_varibales.scss`: You can override the variables in `_variables.scss` to customize the style +* `assets/css/_custom.scss`: You can put your custom css in this file ## Favicons, Browserconfig, Manifest @@ -90,60 +110,60 @@ It is recommended to put your own favicons into `/static`. They’re easily created via [https://realfavicongenerator.net/](https://realfavicongenerator.net/). -Customize browserconfig.xml and site.webmanifest to set theme-color and background-color for example. +Customize `browserconfig.xml` and `site.webmanifest` to set theme-color and background-color. ## Tips -### Set production environment when generating site +### Set `production` environment when generating site -Because some functions are only in production mode, So you **need to add a production** environment variables when generating your site. +Because some features are only in production mode, so you need to add a `production` environment variables when generating your site. ```bash HUGO_ENV=production hugo --gc --minify ``` -### Hugo “extended” Sass/SCSS version required - -This theme write style with scss, So you must download and install the “extended” Sass/SCSS version - ### How to toggle dark-light mode -* You can click the sun logo to toggle dark-light mode. In the desktop version the sun logo is to the right and in the mobile version is positioned to the left, close to the site title. -* If you want to make your own theme toggle-able element, you can create an element with a class `.theme-switch`. See [here](https://github.com/Fastbyte01/KeepIt/blob/master/assets/js/main.js#L32) +* You can click the circle icon to toggle dark-light mode. In the desktop version the circle icon is to the right and in the mobile version is positioned to the left, close to the site title. +* If you want to make your own theme toggle-able element, you can create an element with a class `.theme-switch`. See [here](https://github.com/dillonzq/LoveIt/blob/master/assets/js/blog.js#L14) ## Home Post model -If you want to show posts on index instead of a personal profile, just open config.toml in the base of the Hugo site, add the following line to config.toml +If you want to show posts on index instead of a personal profile, just open `config.toml`, add the following line: ```toml [params] - home_mode = "post" # post or other + home_mode = "post" ``` ## Add logo and cover for SEO -Add a logo image (127x40) and a cover image (800x600). This images are used for SEO. +Add a logo image (127x40) and a cover image (800x600) in the `static` directory. ## Questions, ideas, bugs, pull requests All feedback is welcome! Head over to the [issue tracker](https://github.com/dillonzq/LoveIt/issues). -For more configuration info or other tips you can see the [wiki](https://github.com/dillonzq/LoveIt/wiki). - ## License -LeaveIt is licensed under the MIT license. Check the LICENSE file for details. -The following resources are included in the theme: +LoveIt is licensed under the MIT license. Check the [LICENSE file](https://github.com/dillonzq/LoveIt/blob/master/LICENSE) for details. +Thanks to the authors of following resources included in the theme: + +* [Font Awesome](https://fontawesome.com/) +* [Animate.css](https://daneden.github.io/animate.css/) * [lazysizes](https://github.com/aFarkas/lazysizes) -* [lightGallery](https://github.com/sachinchoolur/lightGallery) -* [code-prettify](https://github.com/google/code-prettify) +* [Smooth Scroll](https://github.com/cferdinandi/smooth-scroll) +* [TypeIt](https://typeitjs.com/) +* [jQuery](https://github.com/jquery/jquery) +* [jQuery.countdown](https://github.com/hilios/jQuery.countdown) +* [Katex](https://katex.org/) +* [mermaid](https://github.com/knsv/mermaid) +* [APlayer](https://github.com/MoePlayer/APlayer) +* [MetingJS](https://github.com/metowolf/MetingJS) +* [Gitalk](https://github.com/gitalk/gitalk) +* [Valine](https://valine.js.org/) ## Author [Dillon](https://dillonzq.com) - -## See Also - -* [Hermitt](https://github.com/Track3/hermit) -* [Goa](https://github.com/shenoybr/hugo-goa) diff --git a/README.zh.md b/README.zh.md new file mode 100644 index 0000000..bd7c931 --- /dev/null +++ b/README.zh.md @@ -0,0 +1,168 @@ +# LoveIt 主题 | Hugo + +[English README](README.md) + +[LoveIt](https://github.com/dillonzq/LoveIt) 是一个**简洁**、**优雅**且**高效**的 [Hugo](https://gohugo.io/) 博客主题。 + +它的原型基于 [LeaveIt 主题](https://github.com/liuzc/LeaveIt/) 和 [KeepIt 主题](https://github.com/liuzc/LeaveIt/)。 + +![Hugo 主题 LoveIt](exampleSite/static/images/Apple-Devices-Preview.png) + +## 主题预览 + +为了直观地浏览主题特性,这里有一个基于 **LoveIt** 主题渲染的 [预览网站](https://hugo-loveit-zh.netlify.com)。 + +使用 **LoveIt** 主题的网站: + +* [Dillon](https://dillonzq.com) +* 你的网站 + +## 特性 + +* 性能优化:在 [Google PageSpeed Insights](https://developers.google.com/speed/pagespeed/insights) 中, 99/100 的移动设备得分和 100/100 的桌面设备得分 +* 桌面设备 / 移动设备 布局的支持 +* 暗黑 / 明亮 模式 +* 使用基于 JSON-LD 格式 的 SEO SCHEMA 文件进行 SEO 优化 +* 页面和列表保持一致的视觉样式 +* 支持多语言和国际化 +* 支持分页 +* 支持 [Google Analytics](https://analytics.google.com/analytics) +* 支持 [Disqus](https://disqus.com) 评论系统 +* 支持 [Gitalk](https://github.com/gitalk/gitalk) 评论系统 +* 支持 [Valine](https://valine.js.org/) 评论系统 +* 支持 [Gravatar](https://gravatar.com) 头像 +* 支持本地头像 +* 支持多达 54 种社交链接 +* 支持文章分享 +* 支持搜索引擎的网站验证 (Google, Bind, Yandex and Baidu) +* 基于 [lazysizes](https://github.com/aFarkas/lazysizes) 自动转换图片为懒加载 +* 基于 Hugo 使用的 chroma 进行代码高亮 +* 使用 [Font Awesome](https://fontawesome.com/) 图标的扩展 Markdown 语法 +* 支持基于 [Katex](https://katex.org/) 的数学公式 +* 支持基于 [mermaid](https://github.com/knsv/mermaid) 的图表和流程图生成功能 +* 支持基于 [APlayer](https://github.com/MoePlayer/APlayer) 和 [MetingJS](https://github.com/metowolf/MetingJS) 的内嵌音乐播放器 +* 支持内嵌 Bilibili 视频 +* 支持多种提醒样式的 shortcode +* 支持自定义对齐和浮动方式的 shortcode +* 支持基于 [TypeIt](https://typeitjs.com/) 的打字动画 +* 支持基于 [jQuery.countdown](https://github.com/hilios/jQuery.countdown) 的倒计时动画 +* 支持基于 [Smooth Scroll](https://github.com/cferdinandi/smooth-scroll) 的回到顶部动画 +* 支持 CDN +* ... + +## 快速开始 + +直接克隆这个代码库到你的 Hugo 主题目录, + +```bash + cd themes + git clone https://github.com/dillonzq/LoveIt.git +``` + +或者,把这个代码库作为子模块。 + +```bash + git submodule add https://github.com/dillonzq/LoveIt.git themes/LoveIt +``` + +下一步, 打开 Hugo 网站的根目录下的 `config.toml` 文件来把 `theme` 设置为 `LoveIt`: + +```bash + theme = "LoveIt" +``` + +更多信息请查看 Hugo 的 [官方安装指南](https://gohugo.io/documentation/)。 + +## 网站设置 + +请看一看 `exampleSite` 目录下的文件。 + +这个目录包含了 `en` 和 `zh` 两种语言的预览网站配置。它可以作为你的网站的配置模板。 + +复制 `config.toml` 文件到你的 Hugo 网站代码根目录。必要的话覆盖原始配置文件。 + +## 目录结构建议 + +以下是一些方便你清晰管理和生成文章的目录结构建议: + +* 保持博客文章存放在 `content/posts` 目录,例如: `content/posts/我的第一篇文章.md` +* 保持简单的静态页面存放在 `content` 目录,例如: `content/about.md` +* 保持图片之类的媒体资源存放在 `static` 目录,例如: `static/images/2019/9/screenshot.png` + +## 为你的网站自定义样式 + +如果你想改变一些网站样式来满足你的需求,你可以编辑: + +* `assets/css/_varibales.scss`: 你可以覆盖 `_variables.scss` 中的变量来自定义样式 +* `assets/css/_custom.scss`: 你可以把自定义的样式放在这个文件 + +## 网站图标、浏览器配置、网站清单 + +强烈建议你把: + +* apple-touch-icon.png (180x180) +* favicon-32x32.png (32x32) +* favicon-16x16.png (16x16) +* mstile-150x150.png (150x150) +* android-chrome-192x192.png (192x192) +* android-chrome-512x512.png (512x512) + +放在 `/static` 目录。利用 [https://realfavicongenerator.net/](https://realfavicongenerator.net/) 可以很容易地生成这些文件。 + +可以自定义 `browserconfig.xml` 和 `site.webmanifest` 文件来设置 theme-color 和 background-color。 + +## 小技巧 + +### 在生成网站时设置 `production` 环境变量 + +由于主题的一些功能仅在生产环境有效,所以你需要在生成网站时设置 `production` 环境变量。 + +```bash + HUGO_ENV=production hugo --gc --minify +``` + +### 怎样切换网站 暗黑-明亮 模式 + +* 你可以点击圆形图标来切换网站 暗黑-明亮 模式。桌面模式下圆形图标在网页右上角,移动设备模式下在网站左上角标题旁边 +* 如果你想自定义切换网站 暗黑-明亮 模式的元素,可以使用一个 class 包含 `.theme-switch` 的元素,详见[此处](https://github.com/dillonzq/LoveIt/blob/master/assets/js/blog.js#L14) + +## 主页预览文章模式 + +如果你想在主页显示文章而不仅仅是个人信息,请打开配置文件 `config.toml`,并增加下面一行: + +```toml + [params] + home_mode = "post" +``` + +## 增加网站 logo 和封面用于 SEO 优化 + +增加一个 logo 图片 (127x40) 和一个封面图片 (800x600) 在 `static` 目录。 + +## 问题、想法、 bugs 和 PRs + +所有的反馈都是欢迎的!详见 [issue tracker](https://github.com/dillonzq/LoveIt/issues)。 + +## 许可协议 + +LoveIt 根据 MIT 许可协议授权。 更多信息请查看 [LICENSE 文件](https://github.com/dillonzq/LoveIt/blob/master/LICENSE)。 + +感谢以下在主题中使用过的项目的作者: + +* [Font Awesome](https://fontawesome.com/) +* [Animate.css](https://daneden.github.io/animate.css/) +* [lazysizes](https://github.com/aFarkas/lazysizes) +* [Smooth Scroll](https://github.com/cferdinandi/smooth-scroll) +* [TypeIt](https://typeitjs.com/) +* [jQuery](https://github.com/jquery/jquery) +* [jQuery.countdown](https://github.com/hilios/jQuery.countdown) +* [Katex](https://katex.org/) +* [mermaid](https://github.com/knsv/mermaid) +* [APlayer](https://github.com/MoePlayer/APlayer) +* [MetingJS](https://github.com/metowolf/MetingJS) +* [Gitalk](https://github.com/gitalk/gitalk) +* [Valine](https://valine.js.org/) + +## 作者 + +[Dillon](https://dillonzq.com) diff --git a/assets/css/_page/_post.scss b/assets/css/_page/_post.scss index b30ea35..e3abe66 100644 --- a/assets/css/_page/_post.scss +++ b/assets/css/_page/_post.scss @@ -159,7 +159,7 @@ .post-dummy-target:target { display: inline-block; position: relative; - top: -5.4rem; + top: -5.6rem; visibility: hidden; } diff --git a/exampleSite/config.toml b/exampleSite/config.toml index b263269..f92e7dd 100644 --- a/exampleSite/config.toml +++ b/exampleSite/config.toml @@ -1,77 +1,128 @@ -baseURL = "https://example.com" -languageCode = "en" -defaultContentLanguage = "en" -title = "KeepIt" -theme = "KeepIt" +baseURL = "/" +languageCode = "en" # website language +defaultContentLanguage = "en" # [en, zh, ...] determines which i18n file to use +title = "LoveIt Theme" # website title +theme = "LoveIt" # theme +enableGitInfo = false # whether to use git commit log to generate lastmod record +hasCJKLanguage = false # whether to include chinese/japanese/korean +paginate = 8 # amount of posts in each page only when home_mode is post +enableEmoji = true # whether to use emoji code +enableRobotsTXT = true # whether to use robots.txt +googleAnalytics = "" # [UA-XXXXXXXX-X] google analytics code +disqusShortname = "dillonzq" # Disqus shortname to use Disqus in posts +copyright = "This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License." + # copyright description used only for seo schema -paginate = 12 -enableEmoji = true -enableRobotsTXT = true -googleAnalytics = "" -disqusShortname = "yourdiscussshortname" + #### Syntax Highlighting (https://gohugo.io/content-management/syntax-highlighting) +pygmentsOptions = "linenos=table" +pygmentsCodefences = true +pygmentsUseClasses = true +pygmentsCodefencesGuessSyntax = true -[sitemap] - changefreq = "monthly" +staticDir = ["static", "themes/LoveIt/assets/others"] # static directories + +[author] #### Author Info + name = "XXXX" + +[sitemap] #### Sitemap Info + changefreq = "weekly" filename = "sitemap.xml" priority = 0.5 -[blackfriday] - hrefTargetBlank = true - nofollowLinks = true - noreferrerLinks = true +[Permalinks] #### Permalinks Info (https://gohugo.io/content-management/urls/#permalinks) + posts = "/:year/:month/:filename/" -[Permalinks] - posts = "/:year/:filename/" - -[menu] +[menu] #### Menu Info [[menu.main]] - name = "Blog" + identifier = "posts" + name = "Posts" url = "/posts/" weight = 1 [[menu.main]] + identifier = "tags" + name = "Tags" + url = "/tags/" + weight = 2 + + [[menu.main]] + identifier = "categories" name = "Categories" url = "/categories/" weight = 3 [[menu.main]] + identifier = "about" name = "About" - url = "/about" + url = "/about/" weight = 4 + [[menu.main]] + identifier = "zh" + name = '' + url = "https://hugo-loveit-zh.netlify.com" + weight = 5 + [params] - since = 2012 - author = "Fastbyte01" # Author's name - subtitle = "A Hugo theme" # Subtitle - cdn_url = "" # Base CDN URL - home_mode = "" # post or other + version = "5.x" # LoveIt theme version + description = "LoveIt Theme Demo" # site description + keywords = ["XXXX", "Theme", "Hugo"] # site keywords - google_verification = "" - bing_verification = "" - yandex_verification = "" - pinterest_verification = "" - baidu_verification = "" - - avatar = "/images/me/avatar.jpg" #comment it to use gravatar - socialShare = true - - description = "" # site description - keywords = "" # site keywords + #### Home Page Info + home_mode = "post" # [post, other] home mode + avatar = "/images/avatar.png" # URL of avatar shown in home page + subtitle = "A Clean, Elegant but Advanced Hugo Theme" # subtitle shown in home page - license= 'Released under CC BY-NC 4.0' + socialShare = true # whether to show social share links in post page -[params.gravatar] - #email = "example@gmail.com" #uncomment and insert your email address to use gravatar + #### Footer CopyRight Info + since = 2018 # Site creation time + icp = '' # ICP info only in China (HTML format is allowed) + license= 'CC BY-NC 4.0' + # license info (HTML format is allowed) + gitRepo = "" # public git repo url to link lastmod git commit only then enableGitInfo is true + linkToMarkdown = true # whether to show link to Raw Markdown content of the post -[params.social] + #### site verification code for Google/Bing/Yandex/Pinterest/Baidu + google_verification = "" + bing_verification = "" + yandex_verification = "" + pinterest_verification = "" + baidu_verification = "" + + [params.cdn] #### CSS and JS Files CDN + fontawesome_free_css = '' # for example '' + animate_css = '' + gitalk_css = '' + gitalk_js = '' + valine_js = '' + jquery_js = '' + lazysizes_js = '' + smooth_scroll_js = '' + katex_css = '' + katex_js = '' + katex_auto_render_js = '' + mermaid_js = '' + echarts_macarons_js = '' + echarts_js = '' + typeit_js = '' + jquery_countdown_js = '' + aplayer_css = '' + aplayer_js = '' + meting_js = '' + + [params.gravatar] # Gravatar Info for preferred avatar in home page + email = "" + + [params.social] # Social Info in home page GitHub = "xxxx" Linkedin = "xxxx" Twitter = "xxxx" #Instagram = "xxxx" - #Email = "xxxx" + #Email = "xxxx" Facebook = "xxxx" - #Telegram = "xxxx" + Telegram = "xxxx" #Medium = "xxxx" #Gitlab = "xxxx" #Youtubelegacy = "xxxx" @@ -84,7 +135,7 @@ disqusShortname = "yourdiscussshortname" #Reddit = "xxxx" #Codepen = "xxxx" #Bitbucket = "xxxx" - #Stackoverflow = "xxxxx" + #Stackoverflow = "xxxx" #Weibo = "xxxx" #Odnoklassniki = "xxxx" #VKontakte = "xxxx" @@ -123,55 +174,72 @@ disqusShortname = "yourdiscussshortname" #Mastodon = "xxxx" #Thingiverse = "xxxx" -[params.share] -Twitter = true -Facebook = true -#Reddit = true -Linkedin = true -#Pinterest = true -#HackerNews = true -#Mix = true -#Tumblr = true -#VKontakte = true -#Douban = true -#Weibo = true - -# Used only for Seo schema -copyright = "This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License." - -[author] - name = "Fastbyte01" - - [params.publisher] - name = "Fastbyte01" + [params.share] # Social Share Links in post page + enable = true + Twitter = true + Facebook = true + Reddit = true + #Linkedin = true + #Pinterest = true + #HackerNews = true + #Mix = true + #Tumblr = true + #VKontakte = true + #Weibo = true + [params.publisher] # Publisher Info just for SEO + name = "XXXX" [params.publisher.logo] - url = "logo.png" + url = "/logo.png" width = 127 height = 40 - [params.logo] - url = "logo.png" + [params.logo] # Website Log Info just for SEO + url = "/logo.png" width = 127 height = 40 - [params.image] - url = "cover.png" + [params.image] # Website Image Info just for SEO + url = "/cover.png" width = 800 height = 600 -[params.gitalk] -owner = "" -repo = "" -clientId = "" -clientSecret = "" + [params.gitalk] # Gittalk Comment Config (https://github.com/gitalk/gitalk) + owner = "" + repo = "" + clientId = "" + clientSecret = "" -[params.valine] - enable = false - appId = 'your appId' - appKey = 'your appKey' - notify = false # mail notifier , https://github.com/xCss/Valine/wiki - verify = false # Verification code - avatar = 'mm' - placeholder = 'your comments ...' - visitor = true + [params.valine] # Valine Comment Config (https://github.com/xCss/Valine) + enable = false + appId = "" + appKey = "" + notify = false + verify = true + avatar = "mp" + placeholder = "Your comment ..." + visitor = true + recordIP = true + +[privacy] #### Privacy Info (https://gohugo.io/about/hugo-and-gdpr/) + [privacy.googleAnalytics] + anonymizeIP = true + + [privacy.youtube] + privacyEnhanced = true + +[mediaTypes] #### Options to make hugo output .md files. + [mediaTypes."text/plain"] + suffixes = ["md"] + +[outputFormats.MarkDown] #### Options to make hugo output .md files. + mediaType = "text/plain" + isPlainText = true + isHTML = false + +[outputs] #### Options to make hugo output .md files. + home = ["HTML", "RSS"] + page = ["HTML", "MarkDown"] + section = ["HTML", "RSS"] + taxonomy = ["HTML", "RSS"] + taxonomyTerm = ["HTML"] diff --git a/exampleSite/content/about.md b/exampleSite/content/about.md index 318d60f..3ba9f50 100644 --- a/exampleSite/content/about.md +++ b/exampleSite/content/about.md @@ -1,20 +1,64 @@ -+++ -title = "About" -date = "2014-04-09" -aliases = ["about-us","about-hugo","contact"] -[ author ] - name = "Hugo Authors" -+++ +--- +title: "About LoveIt" +date: 2019-08-02T11:04:49+08:00 +draft: false +--- -Hugo is the **world’s fastest framework for building websites**. It is written in Go. +[LoveIt :(far fa-heart):](https://github.com/dillonzq/LoveIt) is a **clean**, **elegant** but **advanced** blog theme for [Hugo](https://gohugo.io/) developed by [Dillon](https://dillonzq.com). -It makes use of a variety of open source projects including: +It is based on the original [LeaveIt Theme](https://github.com/liuzc/LeaveIt/) and [KeepIt Theme](https://github.com/liuzc/LeaveIt/). -* https://github.com/russross/blackfriday -* https://github.com/alecthomas/chroma -* https://github.com/muesli/smartcrop -* https://github.com/spf13/cobra -* https://github.com/spf13/viper +![Hugo Theme LoveIt](/images/Apple-Devices-Preview.png) -Learn more and contribute on [GitHub](https://github.com/gohugoio). +### Features +* :(fas fa-rocket): Optimized for performance: 99/100 on mobile and 100/100 on desktop in [Google PageSpeed Insights](https://developers.google.com/speed/pagespeed/insights) +* :(fas fa-desktop): / :(fas fa-mobile): layouts support +* :(fas fa-moon): / :(fas fa-sun): mode +* :(fab fa-searchengin): Optimized SEO performance with a correct SEO SCHEMA based on JSON-LD +* :(fas fa-layer-group): A More coerent style beetwen page and sections +* :(fas fa-language): Multilanguage support and I18N ready +* :(fas fa-ellipsis-h): Pagination support +* :(fab fa-google): [Google Analytics](https://analytics.google.com/analytics) support +* :(far fa-comment): Disqus comment system support by [Disqus](https://disqus.com) +* :(far fa-comment-dots): Gitalk comment system support by [Gitalk](https://github.com/gitalk/gitalk) +* :(far fa-comment-alt): Valine comment system support by [Valine](https://valine.js.org/) +* :(far fa-user): Gravatar support by [Gravatar](https://gravatar.com) +* :(fas fa-user-circle): Local Avatar support +* :(far fa-id-card): Up to 54 social sites supported +* :(fas fa-share-square): Share post support +* :(fas fa-search): Search engine verification support (Google, Bind, Yandex and Baidu) +* :(far fa-images): Automatically converted images with Lazy Load by [lazysizes](https://github.com/aFarkas/lazysizes) +* :(fas fa-code): Automatically highlighting code by chroma in Hugo +* :(fab fa-font-awesome): Extended markdown syntax for [Font Awesome](https://fontawesome.com/) icons +* :(fas fa-square-root-alt): Math formula support by [Katex](https://katex.org/) +* :(fas fa-project-diagram): Diagram syntax shortcode support by [mermaid](https://github.com/knsv/mermaid) +* :(fas fa-music): Embedded music player support by [APlayer](https://github.com/MoePlayer/APlayer) and [MetingJS](https://github.com/metowolf/MetingJS) +* :(fas fa-tv): Bilibili player support +* :(far fa-bell): Kinds of admonitions shortcode support +* :(fas fa-align-left): Custom align and float style shortcodes support +* :(fas fa-i-cursor): Animated typing support by [TypeIt](https://typeitjs.com/) +* :(far fa-clock): Animated coutdown support by [jQuery.countdown](https://github.com/hilios/jQuery.countdown) +* :(fas fa-arrow-up): Dynamic to top support by [Smooth Scroll](https://github.com/cferdinandi/smooth-scroll) +* :(fas fa-tachometer-alt): CDN support +* ... + +### License + +LoveIt is licensed under the MIT license. Check the [LICENSE file](https://github.com/dillonzq/LoveIt/blob/master/LICENSE) for details. + +Thanks to the authors of following resources included in the theme: + +* [Font Awesome](https://fontawesome.com/) +* [Animate.css](https://daneden.github.io/animate.css/) +* [lazysizes](https://github.com/aFarkas/lazysizes) +* [Smooth Scroll](https://github.com/cferdinandi/smooth-scroll) +* [TypeIt](https://typeitjs.com/) +* [jQuery](https://github.com/jquery/jquery) +* [jQuery.countdown](https://github.com/hilios/jQuery.countdown) +* [Katex](https://katex.org/) +* [mermaid](https://github.com/knsv/mermaid) +* [APlayer](https://github.com/MoePlayer/APlayer) +* [MetingJS](https://github.com/metowolf/MetingJS) +* [Gitalk](https://github.com/gitalk/gitalk) +* [Valine](https://valine.js.org/) diff --git a/exampleSite/content/posts/LoveIt-Preview.md b/exampleSite/content/posts/LoveIt-Preview.md new file mode 100644 index 0000000..b9f215d --- /dev/null +++ b/exampleSite/content/posts/LoveIt-Preview.md @@ -0,0 +1,25 @@ +--- +title: "LoveIt Theme Preview and Documentation" +date: 2019-08-25T16:22:42+08:00 +lastmod: 2019-08-25T16:22:42+08:00 +draft: false +description: "This is a LoveIt theme preview and documentation page." +show_in_homepage: true +show_description: false +license: '' + +tags: ['Hugo', 'Theme'] +categories: ['Documentation'] + +featured_image: '' +featured_image_preview: '' + +comment: true +toc: true +autoCollapseToc: true +math: true +--- + +This is a [LoveIt](https://github.com/dillonzq/LoveIt) theme preview and documentation page. + + \ No newline at end of file diff --git a/exampleSite/content/posts/creating-a-new-theme.md b/exampleSite/content/posts/creating-a-new-theme.md deleted file mode 100644 index fa68901..0000000 --- a/exampleSite/content/posts/creating-a-new-theme.md +++ /dev/null @@ -1,1151 +0,0 @@ ---- -author: - name: "Michael Henderson" -date: 2014-09-28 -linktitle: Creating a New Theme -type: -- post -- posts -title: Creating a New Theme -weight: 10 -series: -- Hugo 101 ---- - - -## Introduction - -This tutorial will show you how to create a simple theme in Hugo. I assume that you are familiar with HTML, the bash command line, and that you are comfortable using Markdown to format content. I'll explain how Hugo uses templates and how you can organize your templates to create a theme. I won't cover using CSS to style your theme. - -We'll start with creating a new site with a very basic template. Then we'll add in a few pages and posts. With small variations on that, you will be able to create many different types of web sites. - -In this tutorial, commands that you enter will start with the "$" prompt. The output will follow. Lines that start with "#" are comments that I've added to explain a point. When I show updates to a file, the ":wq" on the last line means to save the file. - -Here's an example: - -``` -## this is a comment -$ echo this is a command -this is a command - -## edit the file -$ vi foo.md -+++ -date = "2014-09-28" -title = "creating a new theme" -+++ - -bah and humbug -:wq - -## show it -$ cat foo.md -+++ -date = "2014-09-28" -title = "creating a new theme" -+++ - -bah and humbug -$ -``` - - -## Some Definitions - -There are a few concepts that you need to understand before creating a theme. - -### Skins - -Skins are the files responsible for the look and feel of your site. It’s the CSS that controls colors and fonts, it’s the Javascript that determines actions and reactions. It’s also the rules that Hugo uses to transform your content into the HTML that the site will serve to visitors. - -You have two ways to create a skin. The simplest way is to create it in the ```layouts/``` directory. If you do, then you don’t have to worry about configuring Hugo to recognize it. The first place that Hugo will look for rules and files is in the ```layouts/``` directory so it will always find the skin. - -Your second choice is to create it in a sub-directory of the ```themes/``` directory. If you do, then you must always tell Hugo where to search for the skin. It’s extra work, though, so why bother with it? - -The difference between creating a skin in ```layouts/``` and creating it in ```themes/``` is very subtle. A skin in ```layouts/``` can’t be customized without updating the templates and static files that it is built from. A skin created in ```themes/```, on the other hand, can be and that makes it easier for other people to use it. - -The rest of this tutorial will call a skin created in the ```themes/``` directory a theme. - -Note that you can use this tutorial to create a skin in the ```layouts/``` directory if you wish to. The main difference will be that you won’t need to update the site’s configuration file to use a theme. - -### The Home Page - -The home page, or landing page, is the first page that many visitors to a site see. It is the index.html file in the root directory of the web site. Since Hugo writes files to the public/ directory, our home page is public/index.html. - -### Site Configuration File - -When Hugo runs, it looks for a configuration file that contains settings that override default values for the entire site. The file can use TOML, YAML, or JSON. I prefer to use TOML for my configuration files. If you prefer to use JSON or YAML, you’ll need to translate my examples. You’ll also need to change the name of the file since Hugo uses the extension to determine how to process it. - -Hugo translates Markdown files into HTML. By default, Hugo expects to find Markdown files in your ```content/``` directory and template files in your ```themes/``` directory. It will create HTML files in your ```public/``` directory. You can change this by specifying alternate locations in the configuration file. - -### Content - -Content is stored in text files that contain two sections. The first section is the “front matter,” which is the meta-information on the content. The second section contains Markdown that will be converted to HTML. - -#### Front Matter - -The front matter is information about the content. Like the configuration file, it can be written in TOML, YAML, or JSON. Unlike the configuration file, Hugo doesn’t use the file’s extension to know the format. It looks for markers to signal the type. TOML is surrounded by “`+++`”, YAML by “`---`”, and JSON is enclosed in curly braces. I prefer to use TOML, so you’ll need to translate my examples if you prefer YAML or JSON. - -The information in the front matter is passed into the template before the content is rendered into HTML. - -#### Markdown - -Content is written in Markdown which makes it easier to create the content. Hugo runs the content through a Markdown engine to create the HTML which will be written to the output file. - -### Template Files - -Hugo uses template files to render content into HTML. Template files are a bridge between the content and presentation. Rules in the template define what content is published, where it's published to, and how it will rendered to the HTML file. The template guides the presentation by specifying the style to use. - -There are three types of templates: single, list, and partial. Each type takes a bit of content as input and transforms it based on the commands in the template. - -Hugo uses its knowledge of the content to find the template file used to render the content. If it can’t find a template that is an exact match for the content, it will shift up a level and search from there. It will continue to do so until it finds a matching template or runs out of templates to try. If it can’t find a template, it will use the default template for the site. - -Please note that you can use the front matter to influence Hugo’s choice of templates. - -#### Single Template - -A single template is used to render a single piece of content. For example, an article or post would be a single piece of content and use a single template. - -#### List Template - -A list template renders a group of related content. That could be a summary of recent postings or all articles in a category. List templates can contain multiple groups. - -The homepage template is a special type of list template. Hugo assumes that the home page of your site will act as the portal for the rest of the content in the site. - -#### Partial Template - -A partial template is a template that can be included in other templates. Partial templates must be called using the “partial” template command. They are very handy for rolling up common behavior. For example, your site may have a banner that all pages use. Instead of copying the text of the banner into every single and list template, you could create a partial with the banner in it. That way if you decide to change the banner, you only have to change the partial template. - -## Create a New Site - -Let's use Hugo to create a new web site. I'm a Mac user, so I'll create mine in my home directory, in the Sites folder. If you're using Linux, you might have to create the folder first. - -The "new site" command will create a skeleton of a site. It will give you the basic directory structure and a useable configuration file. - -``` -$ hugo new site ~/Sites/zafta -$ cd ~/Sites/zafta -$ ls -l -total 8 -drwxr-xr-x 7 quoha staff 238 Sep 29 16:49 . -drwxr-xr-x 3 quoha staff 102 Sep 29 16:49 .. -drwxr-xr-x 2 quoha staff 68 Sep 29 16:49 archetypes --rw-r--r-- 1 quoha staff 82 Sep 29 16:49 config.toml -drwxr-xr-x 2 quoha staff 68 Sep 29 16:49 content -drwxr-xr-x 2 quoha staff 68 Sep 29 16:49 layouts -drwxr-xr-x 2 quoha staff 68 Sep 29 16:49 static -$ -``` - -Take a look in the content/ directory to confirm that it is empty. - -The other directories (archetypes/, layouts/, and static/) are used when customizing a theme. That's a topic for a different tutorial, so please ignore them for now. - -### Generate the HTML For the New Site - -Running the `hugo` command with no options will read all the available content and generate the HTML files. It will also copy all static files (that's everything that's not content). Since we have an empty site, it won't do much, but it will do it very quickly. - -``` -$ hugo --verbose -INFO: 2014/09/29 Using config file: config.toml -INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/static/ to /Users/quoha/Sites/zafta/public/ -WARN: 2014/09/29 Unable to locate layout: [index.html _default/list.html _default/single.html] -WARN: 2014/09/29 Unable to locate layout: [404.html] -0 draft content -0 future content -0 pages created -0 tags created -0 categories created -in 2 ms -$ -``` - -The "`--verbose`" flag gives extra information that will be helpful when we build the template. Every line of the output that starts with "INFO:" or "WARN:" is present because we used that flag. The lines that start with "WARN:" are warning messages. We'll go over them later. - -We can verify that the command worked by looking at the directory again. - -``` -$ ls -l -total 8 -drwxr-xr-x 2 quoha staff 68 Sep 29 16:49 archetypes --rw-r--r-- 1 quoha staff 82 Sep 29 16:49 config.toml -drwxr-xr-x 2 quoha staff 68 Sep 29 16:49 content -drwxr-xr-x 2 quoha staff 68 Sep 29 16:49 layouts -drwxr-xr-x 4 quoha staff 136 Sep 29 17:02 public -drwxr-xr-x 2 quoha staff 68 Sep 29 16:49 static -$ -``` - -See that new public/ directory? Hugo placed all generated content there. When you're ready to publish your web site, that's the place to start. For now, though, let's just confirm that we have what we'd expect from a site with no content. - -``` -$ ls -l public -total 16 --rw-r--r-- 1 quoha staff 416 Sep 29 17:02 index.xml --rw-r--r-- 1 quoha staff 262 Sep 29 17:02 sitemap.xml -$ -``` - -Hugo created two XML files, which is standard, but there are no HTML files. - - - -### Test the New Site - -Verify that you can run the built-in web server. It will dramatically shorten your development cycle if you do. Start it by running the "server" command. If it is successful, you will see output similar to the following: - -``` -$ hugo server --verbose -INFO: 2014/09/29 Using config file: /Users/quoha/Sites/zafta/config.toml -INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/static/ to /Users/quoha/Sites/zafta/public/ -WARN: 2014/09/29 Unable to locate layout: [index.html _default/list.html _default/single.html] -WARN: 2014/09/29 Unable to locate layout: [404.html] -0 draft content -0 future content -0 pages created -0 tags created -0 categories created -in 2 ms -Serving pages from /Users/quoha/Sites/zafta/public -Web Server is available at http://localhost:1313 -Press Ctrl+C to stop -``` - -Connect to the listed URL (it's on the line that starts with "Web Server"). If everything is working correctly, you should get a page that shows the following: - -``` -index.xml -sitemap.xml -``` - -That's a listing of your public/ directory. Hugo didn't create a home page because our site has no content. When there's no index.html file in a directory, the server lists the files in the directory, which is what you should see in your browser. - -Let’s go back and look at those warnings again. - -``` -WARN: 2014/09/29 Unable to locate layout: [index.html _default/list.html _default/single.html] -WARN: 2014/09/29 Unable to locate layout: [404.html] -``` - -That second warning is easier to explain. We haven’t created a template to be used to generate “page not found errors.” The 404 message is a topic for a separate tutorial. - -Now for the first warning. It is for the home page. You can tell because the first layout that it looked for was “index.html.” That’s only used by the home page. - -I like that the verbose flag causes Hugo to list the files that it's searching for. For the home page, they are index.html, _default/list.html, and _default/single.html. There are some rules that we'll cover later that explain the names and paths. For now, just remember that Hugo couldn't find a template for the home page and it told you so. - -At this point, you've got a working installation and site that we can build upon. All that’s left is to add some content and a theme to display it. - -## Create a New Theme - -Hugo doesn't ship with a default theme. There are a few available (I counted a dozen when I first installed Hugo) and Hugo comes with a command to create new themes. - -We're going to create a new theme called "zafta." Since the goal of this tutorial is to show you how to fill out the files to pull in your content, the theme will not contain any CSS. In other words, ugly but functional. - -All themes have opinions on content and layout. For example, Zafta uses "post" over "blog". Strong opinions make for simpler templates but differing opinions make it tougher to use themes. When you build a theme, consider using the terms that other themes do. - - -### Create a Skeleton - -Use the hugo "new" command to create the skeleton of a theme. This creates the directory structure and places empty files for you to fill out. - -``` -$ hugo new theme zafta - -$ ls -l -total 8 -drwxr-xr-x 2 quoha staff 68 Sep 29 16:49 archetypes --rw-r--r-- 1 quoha staff 82 Sep 29 16:49 config.toml -drwxr-xr-x 2 quoha staff 68 Sep 29 16:49 content -drwxr-xr-x 2 quoha staff 68 Sep 29 16:49 layouts -drwxr-xr-x 4 quoha staff 136 Sep 29 17:02 public -drwxr-xr-x 2 quoha staff 68 Sep 29 16:49 static -drwxr-xr-x 3 quoha staff 102 Sep 29 17:31 themes - -$ find themes -type f | xargs ls -l --rw-r--r-- 1 quoha staff 1081 Sep 29 17:31 themes/zafta/LICENSE.md --rw-r--r-- 1 quoha staff 0 Sep 29 17:31 themes/zafta/archetypes/default.md --rw-r--r-- 1 quoha staff 0 Sep 29 17:31 themes/zafta/layouts/_default/list.html --rw-r--r-- 1 quoha staff 0 Sep 29 17:31 themes/zafta/layouts/_default/single.html --rw-r--r-- 1 quoha staff 0 Sep 29 17:31 themes/zafta/layouts/index.html --rw-r--r-- 1 quoha staff 0 Sep 29 17:31 themes/zafta/layouts/partials/footer.html --rw-r--r-- 1 quoha staff 0 Sep 29 17:31 themes/zafta/layouts/partials/header.html --rw-r--r-- 1 quoha staff 93 Sep 29 17:31 themes/zafta/theme.toml -$ -``` - -The skeleton includes templates (the files ending in .html), license file, a description of your theme (the theme.toml file), and an empty archetype. - -Please take a minute to fill out the theme.toml and LICENSE.md files. They're optional, but if you're going to be distributing your theme, it tells the world who to praise (or blame). It's also nice to declare the license so that people will know how they can use the theme. - -``` -$ vi themes/zafta/theme.toml -author = "michael d henderson" -description = "a minimal working template" -license = "MIT" -name = "zafta" -source_repo = "" -tags = ["tags", "categories"] -:wq - -## also edit themes/zafta/LICENSE.md and change -## the bit that says "YOUR_NAME_HERE" -``` - -Note that the the skeleton's template files are empty. Don't worry, we'll be changing that shortly. - -``` -$ find themes/zafta -name '*.html' | xargs ls -l --rw-r--r-- 1 quoha staff 0 Sep 29 17:31 themes/zafta/layouts/_default/list.html --rw-r--r-- 1 quoha staff 0 Sep 29 17:31 themes/zafta/layouts/_default/single.html --rw-r--r-- 1 quoha staff 0 Sep 29 17:31 themes/zafta/layouts/index.html --rw-r--r-- 1 quoha staff 0 Sep 29 17:31 themes/zafta/layouts/partials/footer.html --rw-r--r-- 1 quoha staff 0 Sep 29 17:31 themes/zafta/layouts/partials/header.html -$ -``` - - - -### Update the Configuration File to Use the Theme - -Now that we've got a theme to work with, it's a good idea to add the theme name to the configuration file. This is optional, because you can always add "-t zafta" on all your commands. I like to put it the configuration file because I like shorter command lines. If you don't put it in the configuration file or specify it on the command line, you won't use the template that you're expecting to. - -Edit the file to add the theme, add a title for the site, and specify that all of our content will use the TOML format. - -``` -$ vi config.toml -theme = "zafta" -baseurl = "" -languageCode = "en-us" -title = "zafta - totally refreshing" -MetaDataFormat = "toml" -:wq - -$ -``` - -### Generate the Site - -Now that we have an empty theme, let's generate the site again. - -``` -$ hugo --verbose -INFO: 2014/09/29 Using config file: /Users/quoha/Sites/zafta/config.toml -INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/themes/zafta/static/ to /Users/quoha/Sites/zafta/public/ -INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/static/ to /Users/quoha/Sites/zafta/public/ -WARN: 2014/09/29 Unable to locate layout: [404.html theme/404.html] -0 draft content -0 future content -0 pages created -0 tags created -0 categories created -in 2 ms -$ -``` - -Did you notice that the output is different? The warning message for the home page has disappeared and we have an additional information line saying that Hugo is syncing from the theme's directory. - -Let's check the public/ directory to see what Hugo's created. - -``` -$ ls -l public -total 16 -drwxr-xr-x 2 quoha staff 68 Sep 29 17:56 css --rw-r--r-- 1 quoha staff 0 Sep 29 17:56 index.html --rw-r--r-- 1 quoha staff 407 Sep 29 17:56 index.xml -drwxr-xr-x 2 quoha staff 68 Sep 29 17:56 js --rw-r--r-- 1 quoha staff 243 Sep 29 17:56 sitemap.xml -$ -``` - -Notice four things: - -1. Hugo created a home page. This is the file public/index.html. -2. Hugo created a css/ directory. -3. Hugo created a js/ directory. -4. Hugo claimed that it created 0 pages. It created a file and copied over static files, but didn't create any pages. That's because it considers a "page" to be a file created directly from a content file. It doesn't count things like the index.html files that it creates automatically. - -#### The Home Page - -Hugo supports many different types of templates. The home page is special because it gets its own type of template and its own template file. The file, layouts/index.html, is used to generate the HTML for the home page. The Hugo documentation says that this is the only required template, but that depends. Hugo's warning message shows that it looks for three different templates: - -``` -WARN: 2014/09/29 Unable to locate layout: [index.html _default/list.html _default/single.html] -``` - -If it can't find any of these, it completely skips creating the home page. We noticed that when we built the site without having a theme installed. - -When Hugo created our theme, it created an empty home page template. Now, when we build the site, Hugo finds the template and uses it to generate the HTML for the home page. Since the template file is empty, the HTML file is empty, too. If the template had any rules in it, then Hugo would have used them to generate the home page. - -``` -$ find . -name index.html | xargs ls -l --rw-r--r-- 1 quoha staff 0 Sep 29 20:21 ./public/index.html --rw-r--r-- 1 quoha staff 0 Sep 29 17:31 ./themes/zafta/layouts/index.html -$ -``` - -#### The Magic of Static - -Hugo does two things when generating the site. It uses templates to transform content into HTML and it copies static files into the site. Unlike content, static files are not transformed. They are copied exactly as they are. - -Hugo assumes that your site will use both CSS and JavaScript, so it creates directories in your theme to hold them. Remember opinions? Well, Hugo's opinion is that you'll store your CSS in a directory named css/ and your JavaScript in a directory named js/. If you don't like that, you can change the directory names in your theme directory or even delete them completely. Hugo's nice enough to offer its opinion, then behave nicely if you disagree. - -``` -$ find themes/zafta -type d | xargs ls -ld -drwxr-xr-x 7 quoha staff 238 Sep 29 17:38 themes/zafta -drwxr-xr-x 3 quoha staff 102 Sep 29 17:31 themes/zafta/archetypes -drwxr-xr-x 5 quoha staff 170 Sep 29 17:31 themes/zafta/layouts -drwxr-xr-x 4 quoha staff 136 Sep 29 17:31 themes/zafta/layouts/_default -drwxr-xr-x 4 quoha staff 136 Sep 29 17:31 themes/zafta/layouts/partials -drwxr-xr-x 4 quoha staff 136 Sep 29 17:31 themes/zafta/static -drwxr-xr-x 2 quoha staff 68 Sep 29 17:31 themes/zafta/static/css -drwxr-xr-x 2 quoha staff 68 Sep 29 17:31 themes/zafta/static/js -$ -``` - -## The Theme Development Cycle - -When you're working on a theme, you will make changes in the theme's directory, rebuild the site, and check your changes in the browser. Hugo makes this very easy: - -1. Purge the public/ directory. -2. Run the built in web server in watch mode. -3. Open your site in a browser. -4. Update the theme. -5. Glance at your browser window to see changes. -6. Return to step 4. - -I’ll throw in one more opinion: never work on a theme on a live site. Always work on a copy of your site. Make changes to your theme, test them, then copy them up to your site. For added safety, use a tool like Git to keep a revision history of your content and your theme. Believe me when I say that it is too easy to lose both your mind and your changes. - -Check the main Hugo site for information on using Git with Hugo. - -### Purge the public/ Directory - -When generating the site, Hugo will create new files and update existing ones in the ```public/``` directory. It will not delete files that are no longer used. For example, files that were created in the wrong directory or with the wrong title will remain. If you leave them, you might get confused by them later. I recommend cleaning out your site prior to generating it. - -Note: If you're building on an SSD, you should ignore this. Churning on a SSD can be costly. - -### Hugo's Watch Option - -Hugo's "`--watch`" option will monitor the content/ and your theme directories for changes and rebuild the site automatically. - -### Live Reload - -Hugo's built in web server supports live reload. As pages are saved on the server, the browser is told to refresh the page. Usually, this happens faster than you can say, "Wow, that's totally amazing." - -### Development Commands - -Use the following commands as the basis for your workflow. - -``` -## purge old files. hugo will recreate the public directory. -## -$ rm -rf public -## -## run hugo in watch mode -## -$ hugo server --watch --verbose -``` - -Here's sample output showing Hugo detecting a change to the template for the home page. Once generated, the web browser automatically reloaded the page. I've said this before, it's amazing. - - -``` -$ rm -rf public -$ hugo server --watch --verbose -INFO: 2014/09/29 Using config file: /Users/quoha/Sites/zafta/config.toml -INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/themes/zafta/static/ to /Users/quoha/Sites/zafta/public/ -INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/static/ to /Users/quoha/Sites/zafta/public/ -WARN: 2014/09/29 Unable to locate layout: [404.html theme/404.html] -0 draft content -0 future content -0 pages created -0 tags created -0 categories created -in 2 ms -Watching for changes in /Users/quoha/Sites/zafta/content -Serving pages from /Users/quoha/Sites/zafta/public -Web Server is available at http://localhost:1313 -Press Ctrl+C to stop -INFO: 2014/09/29 File System Event: ["/Users/quoha/Sites/zafta/themes/zafta/layouts/index.html": MODIFY|ATTRIB] -Change detected, rebuilding site - -WARN: 2014/09/29 Unable to locate layout: [404.html theme/404.html] -0 draft content -0 future content -0 pages created -0 tags created -0 categories created -in 1 ms -``` - -## Update the Home Page Template - -The home page is one of a few special pages that Hugo creates automatically. As mentioned earlier, it looks for one of three files in the theme's layout/ directory: - -1. index.html -2. _default/list.html -3. _default/single.html - -We could update one of the default templates, but a good design decision is to update the most specific template available. That's not a hard and fast rule (in fact, we'll break it a few times in this tutorial), but it is a good generalization. - -### Make a Static Home Page - -Right now, that page is empty because we don't have any content and we don't have any logic in the template. Let's change that by adding some text to the template. - -``` -$ vi themes/zafta/layouts/index.html - - - -

hugo says hello!

- - -:wq - -$ -``` - -Build the web site and then verify the results. - -``` -$ hugo --verbose -INFO: 2014/09/29 Using config file: /Users/quoha/Sites/zafta/config.toml -INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/themes/zafta/static/ to /Users/quoha/Sites/zafta/public/ -INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/static/ to /Users/quoha/Sites/zafta/public/ -WARN: 2014/09/29 Unable to locate layout: [404.html theme/404.html] -0 draft content -0 future content -0 pages created -0 tags created -0 categories created -in 2 ms - -$ find public -type f -name '*.html' | xargs ls -l --rw-r--r-- 1 quoha staff 78 Sep 29 21:26 public/index.html - -$ cat public/index.html - - - -

hugo says hello!

- -``` - -#### Live Reload - -Note: If you're running the server with the `--watch` option, you'll see different content in the file: - -``` -$ cat public/index.html - - - -

hugo says hello!

- - -``` - -When you use `--watch`, the Live Reload script is added by Hugo. Look for live reload in the documentation to see what it does and how to disable it. - -### Build a "Dynamic" Home Page - -"Dynamic home page?" Hugo's a static web site generator, so this seems an odd thing to say. I mean let's have the home page automatically reflect the content in the site every time Hugo builds it. We'll use iteration in the template to do that. - -#### Create New Posts - -Now that we have the home page generating static content, let's add some content to the site. We'll display these posts as a list on the home page and on their own page, too. - -Hugo has a command to generate a skeleton post, just like it does for sites and themes. - -``` -$ hugo --verbose new post/first.md -INFO: 2014/09/29 Using config file: /Users/quoha/Sites/zafta/config.toml -INFO: 2014/09/29 attempting to create post/first.md of post -INFO: 2014/09/29 curpath: /Users/quoha/Sites/zafta/themes/zafta/archetypes/default.md -ERROR: 2014/09/29 Unable to Cast to map[string]interface{} - -$ -``` - -That wasn't very nice, was it? - -The "new" command uses an archetype to create the post file. Hugo created an empty default archetype file, but that causes an error when there's a theme. For me, the workaround was to create an archetypes file specifically for the post type. - -``` -$ vi themes/zafta/archetypes/post.md -+++ -Description = "" -Tags = [] -Categories = [] -+++ -:wq - -$ find themes/zafta/archetypes -type f | xargs ls -l --rw-r--r-- 1 quoha staff 0 Sep 29 21:53 themes/zafta/archetypes/default.md --rw-r--r-- 1 quoha staff 51 Sep 29 21:54 themes/zafta/archetypes/post.md - -$ hugo --verbose new post/first.md -INFO: 2014/09/29 Using config file: /Users/quoha/Sites/zafta/config.toml -INFO: 2014/09/29 attempting to create post/first.md of post -INFO: 2014/09/29 curpath: /Users/quoha/Sites/zafta/themes/zafta/archetypes/post.md -INFO: 2014/09/29 creating /Users/quoha/Sites/zafta/content/post/first.md -/Users/quoha/Sites/zafta/content/post/first.md created - -$ hugo --verbose new post/second.md -INFO: 2014/09/29 Using config file: /Users/quoha/Sites/zafta/config.toml -INFO: 2014/09/29 attempting to create post/second.md of post -INFO: 2014/09/29 curpath: /Users/quoha/Sites/zafta/themes/zafta/archetypes/post.md -INFO: 2014/09/29 creating /Users/quoha/Sites/zafta/content/post/second.md -/Users/quoha/Sites/zafta/content/post/second.md created - -$ ls -l content/post -total 16 --rw-r--r-- 1 quoha staff 104 Sep 29 21:54 first.md --rw-r--r-- 1 quoha staff 105 Sep 29 21:57 second.md - -$ cat content/post/first.md -+++ -Categories = [] -Description = "" -Tags = [] -date = "2014-09-29T21:54:53-05:00" -title = "first" - -+++ -my first post - -$ cat content/post/second.md -+++ -Categories = [] -Description = "" -Tags = [] -date = "2014-09-29T21:57:09-05:00" -title = "second" - -+++ -my second post - -$ -``` - -Build the web site and then verify the results. - -``` -$ rm -rf public -$ hugo --verbose -INFO: 2014/09/29 Using config file: /Users/quoha/Sites/zafta/config.toml -INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/themes/zafta/static/ to /Users/quoha/Sites/zafta/public/ -INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/static/ to /Users/quoha/Sites/zafta/public/ -INFO: 2014/09/29 found taxonomies: map[string]string{"category":"categories", "tag":"tags"} -WARN: 2014/09/29 Unable to locate layout: [404.html theme/404.html] -0 draft content -0 future content -2 pages created -0 tags created -0 categories created -in 4 ms -$ -``` - -The output says that it created 2 pages. Those are our new posts: - -``` -$ find public -type f -name '*.html' | xargs ls -l --rw-r--r-- 1 quoha staff 78 Sep 29 22:13 public/index.html --rw-r--r-- 1 quoha staff 0 Sep 29 22:13 public/post/first/index.html --rw-r--r-- 1 quoha staff 0 Sep 29 22:13 public/post/index.html --rw-r--r-- 1 quoha staff 0 Sep 29 22:13 public/post/second/index.html -$ -``` - -The new files are empty because because the templates used to generate the content are empty. The homepage doesn't show the new content, either. We have to update the templates to add the posts. - -### List and Single Templates - -In Hugo, we have three major kinds of templates. There's the home page template that we updated previously. It is used only by the home page. We also have "single" templates which are used to generate output for a single content file. We also have "list" templates that are used to group multiple pieces of content before generating output. - -Generally speaking, list templates are named "list.html" and single templates are named "single.html." - -There are three other types of templates: partials, content views, and terms. We will not go into much detail on these. - -### Add Content to the Homepage - -The home page will contain a list of posts. Let's update its template to add the posts that we just created. The logic in the template will run every time we build the site. - -``` -$ vi themes/zafta/layouts/index.html - - - - {{ range first 10 .Data.Pages }} -

{{ .Title }}

- {{ end }} - - -:wq - -$ -``` - -Hugo uses the Go template engine. That engine scans the template files for commands which are enclosed between "{{" and "}}". In our template, the commands are: - -1. range -2. .Title -3. end - -The "range" command is an iterator. We're going to use it to go through the first ten pages. Every HTML file that Hugo creates is treated as a page, so looping through the list of pages will look at every file that will be created. - -The ".Title" command prints the value of the "title" variable. Hugo pulls it from the front matter in the Markdown file. - -The "end" command signals the end of the range iterator. The engine loops back to the top of the iteration when it finds "end." Everything between the "range" and "end" is evaluated every time the engine goes through the iteration. In this file, that would cause the title from the first ten pages to be output as heading level one. - -It's helpful to remember that some variables, like .Data, are created before any output files. Hugo loads every content file into the variable and then gives the template a chance to process before creating the HTML files. - -Build the web site and then verify the results. - -``` -$ rm -rf public -$ hugo --verbose -INFO: 2014/09/29 Using config file: /Users/quoha/Sites/zafta/config.toml -INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/themes/zafta/static/ to /Users/quoha/Sites/zafta/public/ -INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/static/ to /Users/quoha/Sites/zafta/public/ -INFO: 2014/09/29 found taxonomies: map[string]string{"tag":"tags", "category":"categories"} -WARN: 2014/09/29 Unable to locate layout: [404.html theme/404.html] -0 draft content -0 future content -2 pages created -0 tags created -0 categories created -in 4 ms -$ find public -type f -name '*.html' | xargs ls -l --rw-r--r-- 1 quoha staff 94 Sep 29 22:23 public/index.html --rw-r--r-- 1 quoha staff 0 Sep 29 22:23 public/post/first/index.html --rw-r--r-- 1 quoha staff 0 Sep 29 22:23 public/post/index.html --rw-r--r-- 1 quoha staff 0 Sep 29 22:23 public/post/second/index.html -$ cat public/index.html - - - - -

second

- -

first

- - - -$ -``` - -Congratulations, the home page shows the title of the two posts. The posts themselves are still empty, but let's take a moment to appreciate what we've done. Your template now generates output dynamically. Believe it or not, by inserting the range command inside of those curly braces, you've learned everything you need to know to build a theme. All that's really left is understanding which template will be used to generate each content file and becoming familiar with the commands for the template engine. - -And, if that were entirely true, this tutorial would be much shorter. There are a few things to know that will make creating a new template much easier. Don't worry, though, that's all to come. - -### Add Content to the Posts - -We're working with posts, which are in the content/post/ directory. That means that their section is "post" (and if we don't do something weird, their type is also "post"). - -Hugo uses the section and type to find the template file for every piece of content. Hugo will first look for a template file that matches the section or type name. If it can't find one, then it will look in the _default/ directory. There are some twists that we'll cover when we get to categories and tags, but for now we can assume that Hugo will try post/single.html, then _default/single.html. - -Now that we know the search rule, let's see what we actually have available: - -``` -$ find themes/zafta -name single.html | xargs ls -l --rw-r--r-- 1 quoha staff 132 Sep 29 17:31 themes/zafta/layouts/_default/single.html -``` - -We could create a new template, post/single.html, or change the default. Since we don't know of any other content types, let's start with updating the default. - -Remember, any content that we haven't created a template for will end up using this template. That can be good or bad. Bad because I know that we're going to be adding different types of content and we're going to end up undoing some of the changes we've made. It's good because we'll be able to see immediate results. It's also good to start here because we can start to build the basic layout for the site. As we add more content types, we'll refactor this file and move logic around. Hugo makes that fairly painless, so we'll accept the cost and proceed. - -Please see the Hugo documentation on template rendering for all the details on determining which template to use. And, as the docs mention, if you're building a single page application (SPA) web site, you can delete all of the other templates and work with just the default single page. That's a refreshing amount of joy right there. - -#### Update the Template File - -``` -$ vi themes/zafta/layouts/_default/single.html - - - - {{ .Title }} - - -

{{ .Title }}

- {{ .Content }} - - -:wq - -$ -``` - -Build the web site and verify the results. - -``` -$ rm -rf public -$ hugo --verbose -INFO: 2014/09/29 Using config file: /Users/quoha/Sites/zafta/config.toml -INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/themes/zafta/static/ to /Users/quoha/Sites/zafta/public/ -INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/static/ to /Users/quoha/Sites/zafta/public/ -INFO: 2014/09/29 found taxonomies: map[string]string{"tag":"tags", "category":"categories"} -WARN: 2014/09/29 Unable to locate layout: [404.html theme/404.html] -0 draft content -0 future content -2 pages created -0 tags created -0 categories created -in 4 ms - -$ find public -type f -name '*.html' | xargs ls -l --rw-r--r-- 1 quoha staff 94 Sep 29 22:40 public/index.html --rw-r--r-- 1 quoha staff 125 Sep 29 22:40 public/post/first/index.html --rw-r--r-- 1 quoha staff 0 Sep 29 22:40 public/post/index.html --rw-r--r-- 1 quoha staff 128 Sep 29 22:40 public/post/second/index.html - -$ cat public/post/first/index.html - - - - first - - -

first

-

my first post

- - - - -$ cat public/post/second/index.html - - - - second - - -

second

-

my second post

- - - -$ -``` - -Notice that the posts now have content. You can go to localhost:1313/post/first to verify. - -### Linking to Content - -The posts are on the home page. Let's add a link from there to the post. Since this is the home page, we'll update its template. - -``` -$ vi themes/zafta/layouts/index.html - - - - {{ range first 10 .Data.Pages }} -

{{ .Title }}

- {{ end }} - - -``` - -Build the web site and verify the results. - -``` -$ rm -rf public -$ hugo --verbose -INFO: 2014/09/29 Using config file: /Users/quoha/Sites/zafta/config.toml -INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/themes/zafta/static/ to /Users/quoha/Sites/zafta/public/ -INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/static/ to /Users/quoha/Sites/zafta/public/ -INFO: 2014/09/29 found taxonomies: map[string]string{"tag":"tags", "category":"categories"} -WARN: 2014/09/29 Unable to locate layout: [404.html theme/404.html] -0 draft content -0 future content -2 pages created -0 tags created -0 categories created -in 4 ms - -$ find public -type f -name '*.html' | xargs ls -l --rw-r--r-- 1 quoha staff 149 Sep 29 22:44 public/index.html --rw-r--r-- 1 quoha staff 125 Sep 29 22:44 public/post/first/index.html --rw-r--r-- 1 quoha staff 0 Sep 29 22:44 public/post/index.html --rw-r--r-- 1 quoha staff 128 Sep 29 22:44 public/post/second/index.html - -$ cat public/index.html - - - - -

second

- -

first

- - - - -$ -``` - -### Create a Post Listing - -We have the posts displaying on the home page and on their own page. We also have a file public/post/index.html that is empty. Let's make it show a list of all posts (not just the first ten). - -We need to decide which template to update. This will be a listing, so it should be a list template. Let's take a quick look and see which list templates are available. - -``` -$ find themes/zafta -name list.html | xargs ls -l --rw-r--r-- 1 quoha staff 0 Sep 29 17:31 themes/zafta/layouts/_default/list.html -``` - -As with the single post, we have to decide to update _default/list.html or create post/list.html. We still don't have multiple content types, so let's stay consistent and update the default list template. - -## Creating Top Level Pages - -Let's add an "about" page and display it at the top level (as opposed to a sub-level like we did with posts). - -The default in Hugo is to use the directory structure of the content/ directory to guide the location of the generated html in the public/ directory. Let's verify that by creating an "about" page at the top level: - -``` -$ vi content/about.md -+++ -title = "about" -description = "about this site" -date = "2014-09-27" -slug = "about time" -+++ - -## about us - -i'm speechless -:wq -``` - -Generate the web site and verify the results. - -``` -$ find public -name '*.html' | xargs ls -l --rw-rw-r-- 1 mdhender staff 334 Sep 27 15:08 public/about-time/index.html --rw-rw-r-- 1 mdhender staff 527 Sep 27 15:08 public/index.html --rw-rw-r-- 1 mdhender staff 358 Sep 27 15:08 public/post/first-post/index.html --rw-rw-r-- 1 mdhender staff 0 Sep 27 15:08 public/post/index.html --rw-rw-r-- 1 mdhender staff 342 Sep 27 15:08 public/post/second-post/index.html -``` - -Notice that the page wasn't created at the top level. It was created in a sub-directory named 'about-time/'. That name came from our slug. Hugo will use the slug to name the generated content. It's a reasonable default, by the way, but we can learn a few things by fighting it for this file. - -One other thing. Take a look at the home page. - -``` -$ cat public/index.html - - - -

creating a new theme

-

about

-

second

-

first

- - -``` - -Notice that the "about" link is listed with the posts? That's not desirable, so let's change that first. - -``` -$ vi themes/zafta/layouts/index.html - - - -

posts

- {{ range first 10 .Data.Pages }} - {{ if eq .Type "post"}} -

{{ .Title }}

- {{ end }} - {{ end }} - -

pages

- {{ range .Data.Pages }} - {{ if eq .Type "page" }} -

{{ .Title }}

- {{ end }} - {{ end }} - - -:wq -``` - -Generate the web site and verify the results. The home page has two sections, posts and pages, and each section has the right set of headings and links in it. - -But, that about page still renders to about-time/index.html. - -``` -$ find public -name '*.html' | xargs ls -l --rw-rw-r-- 1 mdhender staff 334 Sep 27 15:33 public/about-time/index.html --rw-rw-r-- 1 mdhender staff 645 Sep 27 15:33 public/index.html --rw-rw-r-- 1 mdhender staff 358 Sep 27 15:33 public/post/first-post/index.html --rw-rw-r-- 1 mdhender staff 0 Sep 27 15:33 public/post/index.html --rw-rw-r-- 1 mdhender staff 342 Sep 27 15:33 public/post/second-post/index.html -``` - -Knowing that hugo is using the slug to generate the file name, the simplest solution is to change the slug. Let's do it the hard way and change the permalink in the configuration file. - -``` -$ vi config.toml -[permalinks] - page = "/:title/" - about = "/:filename/" -``` - -Generate the web site and verify that this didn't work. Hugo lets "slug" or "URL" override the permalinks setting in the configuration file. Go ahead and comment out the slug in content/about.md, then generate the web site to get it to be created in the right place. - -## Sharing Templates - -If you've been following along, you probably noticed that posts have titles in the browser and the home page doesn't. That's because we didn't put the title in the home page's template (layouts/index.html). That's an easy thing to do, but let's look at a different option. - -We can put the common bits into a shared template that's stored in the themes/zafta/layouts/partials/ directory. - -### Create the Header and Footer Partials - -In Hugo, a partial is a sugar-coated template. Normally a template reference has a path specified. Partials are different. Hugo searches for them along a TODO defined search path. This makes it easier for end-users to override the theme's presentation. - -``` -$ vi themes/zafta/layouts/partials/header.html - - - - {{ .Title }} - - -:wq - -$ vi themes/zafta/layouts/partials/footer.html - - -:wq -``` - -### Update the Home Page Template to Use the Partials - -The most noticeable difference between a template call and a partials call is the lack of path: - -``` -{{ template "theme/partials/header.html" . }} -``` -versus -``` -{{ partial "header.html" . }} -``` -Both pass in the context. - -Let's change the home page template to use these new partials. - -``` -$ vi themes/zafta/layouts/index.html -{{ partial "header.html" . }} - -

posts

- {{ range first 10 .Data.Pages }} - {{ if eq .Type "post"}} -

{{ .Title }}

- {{ end }} - {{ end }} - -

pages

- {{ range .Data.Pages }} - {{ if or (eq .Type "page") (eq .Type "about") }} -

{{ .Type }} - {{ .Title }} - {{ .RelPermalink }}

- {{ end }} - {{ end }} - -{{ partial "footer.html" . }} -:wq -``` - -Generate the web site and verify the results. The title on the home page is now "your title here", which comes from the "title" variable in the config.toml file. - -### Update the Default Single Template to Use the Partials - -``` -$ vi themes/zafta/layouts/_default/single.html -{{ partial "header.html" . }} - -

{{ .Title }}

- {{ .Content }} - -{{ partial "footer.html" . }} -:wq -``` - -Generate the web site and verify the results. The title on the posts and the about page should both reflect the value in the markdown file. - -## Add “Date Published” to Posts - -It's common to have posts display the date that they were written or published, so let's add that. The front matter of our posts has a variable named "date." It's usually the date the content was created, but let's pretend that's the value we want to display. - -### Add “Date Published” to the Template - -We'll start by updating the template used to render the posts. The template code will look like: - -``` -{{ .Date.Format "Mon, Jan 2, 2006" }} -``` - -Posts use the default single template, so we'll change that file. - -``` -$ vi themes/zafta/layouts/_default/single.html -{{ partial "header.html" . }} - -

{{ .Title }}

-

{{ .Date.Format "Mon, Jan 2, 2006" }}

- {{ .Content }} - -{{ partial "footer.html" . }} -:wq -``` - -Generate the web site and verify the results. The posts now have the date displayed in them. There's a problem, though. The "about" page also has the date displayed. - -As usual, there are a couple of ways to make the date display only on posts. We could do an "if" statement like we did on the home page. Another way would be to create a separate template for posts. - -The "if" solution works for sites that have just a couple of content types. It aligns with the principle of "code for today," too. - -Let's assume, though, that we've made our site so complex that we feel we have to create a new template type. In Hugo-speak, we're going to create a section template. - -Let's restore the default single template before we forget. - -``` -$ mkdir themes/zafta/layouts/post -$ vi themes/zafta/layouts/_default/single.html -{{ partial "header.html" . }} - -

{{ .Title }}

- {{ .Content }} - -{{ partial "footer.html" . }} -:wq -``` - -Now we'll update the post's version of the single template. If you remember Hugo's rules, the template engine will use this version over the default. - -``` -$ vi themes/zafta/layouts/post/single.html -{{ partial "header.html" . }} - -

{{ .Title }}

-

{{ .Date.Format "Mon, Jan 2, 2006" }}

- {{ .Content }} - -{{ partial "footer.html" . }} -:wq - -``` - -Note that we removed the date logic from the default template and put it in the post template. Generate the web site and verify the results. Posts have dates and the about page doesn't. - -### Don't Repeat Yourself - -DRY is a good design goal and Hugo does a great job supporting it. Part of the art of a good template is knowing when to add a new template and when to update an existing one. While you're figuring that out, accept that you'll be doing some refactoring. Hugo makes that easy and fast, so it's okay to delay splitting up a template. diff --git a/exampleSite/content/posts/goisforlovers.fr.md b/exampleSite/content/posts/goisforlovers.fr.md deleted file mode 100644 index 80ec632..0000000 --- a/exampleSite/content/posts/goisforlovers.fr.md +++ /dev/null @@ -1,352 +0,0 @@ -+++ -categories = ["Go"] -date = "2014-04-02" -description = "" -featured = "pic02.jpg" -featuredalt = "" -featuredpath = "date" -linktitle = "" -slug = "Introduction aux modeles Hugo" -title = "Introduction aux modèles (Hu)go" -type = ["posts","post"] -[ author ] - name = "Michael Henderson" -+++ - -Hugo utilise l'excellente librairie [go][] [html/template][gohtmltemplate] pour -son moteur de modèles. c'est un moteur extrêmement léger qui offre un très petit -nombre de fonctions logiques. À notre expérience, c'est juste ce qu'il faut pour -créer un bon site web statique. Si vous avez déjà utilisé d'autre moteurs de -modèles pour différents langages ou frameworks, vous allez retrouver beaucoup de -similitudes avec les modèles go. - -Ce document est une introduction sur l'utilisation de Go templates. La -[documentation go][gohtmltemplate] fourni plus de détails. - -## Introduction aux modèles Go - -Go templates fournit un langage de modèles très simple. Il adhère à la -conviction que les modèles ou les vues doivent avoir une logique des plus -élémentaires. L'une des conséquences de cette simplicité est que les modèles -seront plus rapides a être analysés. - -Une caractéristique unique de Go templates est qu'il est conscient du contenu. -Les variables et le contenu va être nettoyé suivant le contexte d'utilisation. -Plus de détails sont disponibles dans la [documentation go][gohtmltemplate]. - -## Syntaxe basique - -Les modèles en langage Go sont des fichiers HTML avec l'ajout de variables et -fonctions. - -**Les variables Go et les fonctions sont accessibles avec {{ }}** - - -Accès à une variable prédéfinie "foo": - - {{ foo }} - -**Les paramètres sont séparés par des espaces** - -Appel de la fonction add avec 1 et 2 en argument** - - {{ add 1 2 }} - -**Les méthodes et les champs sont accessibles par un point** - -Accès au paramètre de la page "bar" - - {{ .Params.bar }} - -**Les parenthèses peuvent être utilisées pour grouper des éléments ensemble** -``` -{{ if or (isset .Params "alt") (isset .Params "caption") }} Caption {{ end }} -``` - -## Variables - -Chaque modèle go a une structure (objet) mis à sa disposition. Avec Hugo, à -chaque modèle est passé soit une page, soit une structure de nœud, suivant quel -type de page vous rendez. Plus de détails sont disponibles sur la page des -[variables](/layout/variables). - -Une variable est accessible par son nom. - - {{ .Title }} - -Les variables peuvent également être définies et appelées. - - {{ $address := "123 Main St."}} - {{ $address }} - - -## Functions - -Go templace est livré avec quelques fonctions qui fournissent des -fonctionnalités basiques. Le système de Go template fourni également un -mécanisme permettant aux applications d'étendre les fonctions disponible. Les -[fonctions de modèle Hugo](/layout/functions) fourni quelques fonctionnalités -supplémentaires que nous espérons qu'elles seront utiles pour vos sites web. -Les functions sont appelées en utilisant leur nom suivi par les paramètres -requis séparés par des espaces. Des fonctions de modèles ne peuvent pas être -ajoutées sans recompiler Hugo. - -**Exemple:** - - {{ add 1 2 }} - -## Inclusions - -Lorsque vous incluez un autre modèle, vous devez y passer les données qu'il sera -en mesure d'accèder. Pour passer le contexte actuel, pensez à ajouter un point. -La localisation du modèle sera toujours à partir du répertoire /layout/ dans -Hugo. - -**Exemple:** - - {{ template "chrome/header.html" . }} - - -## Logique - -Go templates fourni les itérations et la logique conditionnèle des plus basique. - -### Itération - -Comme en go, les modèles go utilisent fortement *range* pour itérer dans une -map, un array ou un slice. Les exemples suivant montre différentes façons -d'utiliser *range* - -**Exemple 1: En utilisant le context** - - {{ range array }} - {{ . }} - {{ end }} - -**Exemple 2: En déclarant un nom de variable** - - {{range $element := array}} - {{ $element }} - {{ end }} - -**Exemple 2: En déclarant un nom de varialbe pour la clé et la valeur** - - {{range $index, $element := array}} - {{ $index }} - {{ $element }} - {{ end }} - -### Conditions - -*If*, *else*, *with*, *or*, *&*, *and* fournissent la base pour la logique -conditionnelle avec Go templates. Comme *range*, chaque déclaration est fermé -avec `end`. - -Go templates considère les valeurs suivante comme *false* : - -* false -* 0 -* tout array, slice, map ou chaine d'une longueur de zéro - -**Exemple 1: If** - - {{ if isset .Params "title" }}

{{ index .Params "title" }}

{{ end }} - -**Exemple 2: If -> Else** - - {{ if isset .Params "alt" }} - {{ index .Params "alt" }} - {{else}} - {{ index .Params "caption" }} - {{ end }} - -**Exemple 3: And & Or** -``` -{{ if and (or (isset .Params "title") (isset .Params "caption")) - (isset .Params "attr")}} -``` -**Exemple 4: With** - -Une manière alternative d'écrire un "if" et de référencer cette même valeur est -d'utiliser "with". Cela permet de remplacer le contexte `.` par cet valeur et -saute le bloc si la variable est absente. - -Le premier exemple peut être simplifié à ceci : - - {{ with .Params.title }}

{{ . }}

{{ end }} - -**Exemple 5: If -> Else If** - - {{ if isset .Params "alt" }} - {{ index .Params "alt" }} - {{ else if isset .Params "caption" }} - {{ index .Params "caption" }} - {{ end }} - -## *Pipes* - -L'un des composants le plus puissant de Go templates est la capacité d'empiler -les action l'une après l'autre. Cela est fait en utilisant les *pipes*. -Empruntés aux *pipes* unix, le concept est simple. Chaque sortie de *pipeline* -devient l'entrée du *pipe* suivant. - -À cause de la syntaxe très simple de Go templates, le *pipe* est essentiel pour -être capable d'enchainer les appels de fonctions. Une limitation des *pipes* -est qu'il ne peuvent fonctionner seulement avec une seule valeur et cette valeur -devient le dernier paramètre du prochain *pipeline*. - -Quelques exemples simple devrait vous aider à comprendre comment utiliser les -*pipes*. - -**Exemple 1 :** - - {{ if eq 1 1 }} Same {{ end }} - -est identique à - - {{ eq 1 1 | if }} Same {{ end }} - - -Il semble étrange de placer le *if* à la fin, mais il fournit une bonne -illustration de la façon d'utiliser les tuyaux. - -**Exemple 2 :** - - {{ index .Params "disqus_url" | html }} - -Accès au paramètre de page nommé "disqus_url" et échappement du HTML - -**Exemple 3 :** -``` -{{ if or (or (isset .Params "title") (isset .Params "caption")) - (isset .Params "attr")}} -Stuff Here -{{ end }} -``` -Peut être réécrit en - -``` -{{ isset .Params "caption" | or isset .Params "title" | - or isset .Params "attr" | if }} -Stuff Here -{{ end }} -``` - -## Contexte (alias. le point) - -Le concept le plus facilement négligé pour comprendre les modèles go est que -{{ . }} fait toujours référence au contexte actuel. Dans le plus haut niveau de -votre modèle, ce sera l'ensemble des données mis à votre disposition. Dans une -itération, ce sera la valeur de l'élément actuel. Enfin, dans une boucle, le -contexte change. . ne fera plus référence aux données disponibles dans la page -entière. Si vous avez besoin y d'accèder depuis l'intérieur d'une boucle, il est -judicieux d'y définir comme variable au lieu de dépendre du contexte. - -**Exemple:** -``` -{{ $title := .Site.Title }} -{{ range .Params.tags }} -
  • - {{ . }} - {{ $title }}
  • -{{ end }} -``` - -Notez que, une fois que nous sommes entrés dans la boucle, la valeur de -{{ . }} a changée. Nous avons défini une variable en dehors de la boucle, afin -d'y avoir accès dans la boucle. - -# Les Paramètres d'Hugo - -Hugo fournit l'option de passer des valeurs au modèle depuis la configuration du -site, ou depuis les métadonnées de chaque partie du contenu. Vous pouvez définir -n'importe quelle valeur de n'importe quel type (supporté par votre section -liminaire / format de configuration) et les utiliser comme vous le souhaitez -dans votre modèle. - -## Utiliser les paramètres de contenu (page) - -Dans chaque partie du contenu, vous pouvez fournir des variables pour être -utilisées par le modèle. Cela se passe dans la -[section liminaire](/content/front-matter). - -Un exemple de cela est utilisé par ce site de documentation. La plupart des -pages bénéficient de la présentation de la table des matières. Quelques fois, -la table des matières n'a pas beaucoup de sens. Nous avons défini une variable -dans notre section liminaire de quelques pages pour désactiver la table des -matières. - -Ceci est un exemple de section liminaire : - -``` ---- -title: "Permalinks" -date: "2013-11-18" -aliases: - - "/doc/permalinks/" -groups: ["extras"] -groups_weight: 30 -notoc: true ---- -``` - -Ceci est le code correspondant dans le modèle : - - {{ if not .Params.notoc }} -
    - {{ .TableOfContents }} -
    - {{ end }} - - - -## Utiliser les paramètres de site (config) - -Dans votre configuration de plus haut niveau (ex `config.yaml`), vous pouvez -définir des paramètres de site, dont les valeurs vous seront accessibles. - -Pour les instances, vous pourriez délarer : - -```yaml -params: - CopyrightHTML: "Copyright © 2013 John Doe. All Rights Reserved." - TwitterUser: "spf13" - SidebarRecentLimit: 5 -``` - -Avec un pied de page, vous devriez déclarer un `