公告
markdown
syntaxBasic usage /posts/hugo/basic-usage/ Test your installation After [installing] Hugo, test your installation by running: ```bash hugo version ``` You should see something like: ```text hugo v0.105.0-0e3b42b4a9bdeb4d866210819fc6ddcf51582ffa+extended linux/amd64 BuildDate=2022-10-28T12:29:05Z VendorInfo=snap:0.105.0 ``` Display available commands To see a list of the available commands and flags: ```bash hugo help ``` To get help with a subcommand, use the `--help` flag. For example: ```bash hugo server --help ``` Build your site To build your site, `cd` into your project directory and run: ```bash hugo ``` The [`hugo`] command builds your site, publishing the files to the `public` directory. To publish your site to a different directory, use the [`--destination`] flag or set [`publishDir`] in your site configuration. Draft, future, and expired content Hugo allows you to set `draft`, `date`, `publishDate`, and `expiryDate` in the [front matter] of your content. By default, Hugo will not publish content when: - The `draft` value is `true` - The `date` is in the future - The `publishDate` is in the future - The `expiryDate` is in the past You can override the default behavior when running `hugo` or `hugo server` with command line flags: ```bash hugo --buildDrafts or -D hugo --buildExpired or -E hugo --buildFuture or -F ``` Although you can also set these values in your site configuration, it can lead to unwanted results unless all content authors are aware of, and understand, the settings. Develop and test your site To view your site while developing layouts or creating content, `cd` into your project directory and run: ```bash hugo server ``` The [`hugo server`] command builds your site into memory, and serves your pages using a minimal HTTP server. When you run `hugo server` it will display the URL of your local site: ```text Web Server is available at http://localhost:1313/ ``` While the server is running, it watches your project directory for changes to assets, configuration, content, data, layouts, translations, and static files. When it detects a change, the server rebuilds your site and refreshes your browser using [LiveReload]. Most Hugo builds are so fast that you may not notice the change unless you are looking directly at your browser. LiveReload While the server is running, Hugo injects JavaScript into the generated HTML pages. The LiveReload script creates a connection from the browser to the server via web sockets. You do not need to install any software or browser plugins, nor is any configuration required. Automatic redirection When editing content, if you want your browser to automatically redirect to the page you last modified, run: ```bash hugo server --navigateToChanged ``` Deploy your site When you are ready to deploy your site, run: ```bash hugo ``` This builds your site, publishing the files to the public directory. The directory structure will look something like this: ```text public/ ├── categories/ │ ├── index.html │ └── index.xml <-- RSS feed for this section ├── post/ │ ├── my-first-post/ │ │ └── index.html │ ├── index.html │ └── index.xml <-- RSS feed for this section ├── tags/ │ ├── index.html │ └── index.xml <-- RSS feed for this section ├── index.html ├── index.xml <-- RSS feed for the site └── sitemap.xml ``` In a simple hosting environment, where you typically `ftp`, `rsync`, or `scp` your files to the root of a virtual host, the contents of the `public` directory are all that you need. Most of our users deploy their sites using a CI/CD workflow, where a push[^1] to their GitHub or GitLab repository triggers a build and deployment. Popular providers include [AWS Amplify], [CloudCannon], [Cloudflare Pages], [GitHub Pages], [GitLab Pages], and [Netlify]. Learn more in the [hosting and deployment] section. [^1]: The Git repository contains the entire project directory, typically excluding the public directory because the site is built _after_ the push. [`--destination`]: /commands/hugo/options [`hugo server`]: /commands/hugo_server/ [`hugo`]: /commands/hugo/ [`publishDir`]: /getting-started/configuration/publishdir [AWS Amplify]: https://aws.amazon.com/amplify/ [CloudCannon]: https://cloudcannon.com/ [Cloudflare Pages]: https://pages.cloudflare.com/ [commands]: /commands/ [front matter]: /content-management/front-matter/ [GitHub Pages]: https://pages.github.com/ [GitLab Pages]: https://docs.gitlab.com/ee/user/project/pages/ [hosting and deployment]: /hosting-and-deployment/ [hosting]: /hosting-and-deployment/ [installing]: /installation/ [LiveReload]: https://github.com/livereload/livereload-js [Netlify]: https://www.netlify.com/ (Hu)go Template Primer /posts/hugo/hugo-template-primer/ Hugo uses the excellentGo][] [html/template][gohtmltemplate] library for its template engine. It is an extremely lightweight engine that provides a very small amount of logic. In our experience that it is just the right amount of logic to be able to create a good static website. If you have used other template systems from different languages or frameworks you will find a lot of similarities in Go templates. This document is a brief primer on using Go templates. The [Go docs][gohtmltemplate] provide more details. Introduction to Go Templates Go templates provide an extremely simple template language. It adheres to the belief that only the most basic of logic belongs in the template or view layer. One consequence of this simplicity is that Go templates parse very quickly. A unique characteristic of Go templates is they are content aware. Variables and content will be sanitized depending on the context of where they are used. More details can be found in the [Go docs][gohtmltemplate]. Basic Syntax Golang templates are HTML files with the addition of variables and functions. **Go variables and functions are accessible within ** Accessing a predefined variable "foo": **Parameters are separated using spaces** Calling the add function with input of 1, 2: **Methods and fields are accessed via dot notation** Accessing the Page Parameter "bar" **Parentheses can be used to group items together** Caption Variables Each Go template has a struct (object) made available to it. In hugo each template is passed either a page or a node struct depending on which type of page you are rendering. More details are available on the [variablespage. A variable is accessed by referencing the variable name. <title></title> Variables can also be defined and referenced. Functions Go template ship with a few functions which provide basic functionality. The Go template system also provides a mechanism for applications to extend the available functions with their own.Hugo template functionsprovide some additional functionality we believe are useful for building websites. Functions are called by using their name followed by the required parameters separated by spaces. Template functions cannot be added without recompiling hugo. **Example:** Includes When including another template you will pass to it the data it will be able to access. To pass along the current context please remember to include a trailing dot. The templates location will always be starting at the /layout/ directory within Hugo. **Example:** Logic Go templates provide the most basic iteration and conditional logic. Iteration Just like in Go, the Go templates make heavy use of range to iterate over a map, array or slice. The following are different examples of how to use range. **Example 1: Using Context** **Example 2: Declaring value variable name** **Example 2: Declaring key and value variable name** Conditionals If, else, with, or, & and provide the framework for handling conditional logic in Go Templates. Like range, each statement is closed with `end`. Go Templates treat the following values as false: * false * 0 * any array, slice, map, or string of length zero **Example 1: If** <h4></h4> **Example 2: If -> Else** **Example 3: And & Or** **Example 4: With** An alternative way of writing "if" and then referencing the same value is to use "with" instead. With rebinds the context `.` within its scope, and skips the block if the variable is absent. The first example above could be simplified as: <h4></h4> **Example 5: If -> Else If** Pipes One of the most powerful components of Go templates is the ability to stack actions one after another. This is done by using pipes. Borrowed from unix pipes, the concept is simple, each pipeline's output becomes the input of the following pipe. Because of the very simple syntax of Go templates, the pipe is essential to being able to chain together function calls. One limitation of the pipes is that they only can work with a single value and that value becomes the last parameter of the next pipeline. A few simple examples should help convey how to use the pipe. **Example 1 :** Same is the same as Same It does look odd to place the if at the end, but it does provide a good illustration of how to use the pipes. **Example 2 :** Access the page parameter called "disqus_url" and escape the HTML. **Example 3 :** Stuff Here Could be rewritten as Stuff Here Context (aka. the dot) The most easily overlooked concept to understand about Go templates is that always refers to the current context. In the top level of your template this will be the data set made available to it. Inside of a iteration it will have the value of the current item. When inside of a loop the context has changed. . will no longer refer to the data available to the entire page. If you need to access this from within the loop you will likely want to set it to a variable instead of depending on the context. **Example:** <li> <a href="/tags/"></a> - </li> Notice how once we have entered the loop the value of has changed. We have defined a variable outside of the loop so we have access to it from within the loop. Hugo Parameters Hugo provides the option of passing values to the template language through the site configuration (for sitewide values), or through the meta data of each specific piece of content. You can define any values of any type (supported by your front matter/config format) and use them however you want to inside of your templates. Using Content (page) Parameters In each piece of content you can provide variables to be used by the templates. This happens in thefront matter. An example of this is used in this documentation site. Most of the pages benefit from having the table of contents provided. Sometimes the TOC just doesn't make a lot of sense. We've defined a variable in our front matter of some pages to turn off the TOC from being displayed. Here is the example front matter: ``` --- title: "Permalinks" date: "2013-11-18" aliases: - "/doc/permalinks/" groups: ["extras"] groups_weight: 30 notoc: true --- ``` Here is the corresponding code inside of the template: <div id="toc" class="well col-md-4 col-sm-6"> </div> Using Site (config) Parameters In your top-level configuration file (eg, `config.yaml`) you can define site parameters, which are values which will be available to you in chrome. For instance, you might declare: ```yaml params: CopyrightHTML: "Copyright &xA9; 2013 John Doe. All Rights Reserved." TwitterUser: "spf13" SidebarRecentLimit: 5 ``` Within a footer layout, you might then declare a `<footer>` which is only provided if the `CopyrightHTML` parameter is provided, and if it is given, you would declare it to be HTML-safe, so that the HTML entity is not escaped again. This would let you easily update just your top-level config file each January 1st, instead of hunting through your templates. ``` <footer> <div class="text-center"></div> </footer> ``` An alternative way of writing the "if" and then referencing the same value is to use "with" instead. With rebinds the context `.` within its scope, and skips the block if the variable is absent: ``` <span class="twitter"> <a href="https://twitter.com/" rel="author"> <img src="/images/twitter.png" width="48" height="48" title="Twitter: " alt="Twitter"></a> </span> ``` Finally, if you want to pull "magic constants" out of your layouts, you can do so, such as in this example: ``` <nav class="recent"> <h1>Recent Posts</h1> <ul> <li><a href=""></a></li> </ul> </nav> ``` [go]: https://golang.org/ [gohtmltemplate]: https://golang.org/pkg/html/template/ Getting Started with Hugo /posts/hugo/getting-started-with-hugo/ Step 1. Install Hugo Go toHugo releasesand download the appropriate version for your OS and architecture. Save it somewhere specific as we will be using it in the next step. More complete instructions are available atInstall Hugo Step 2. Build the Docs Hugo has its own example site which happens to also be the documentation site you are reading right now. Follow the following steps: 1. Clone theHugo repository2. Go into the repo 3. Run hugo in server mode and build the docs 4. Open your browser to http://localhost:1313 Corresponding pseudo commands: ``` git clone https://github.com/spf13/hugo cd hugo /path/to/where/you/installed/hugo server --source=./docs > 29 pages created > 0 tags index created > in 27 ms > Web Server is available at http://localhost:1313 > Press ctrl+c to stop ``` Once you've gotten here, follow along the rest of this page on your local build. Step 3. Change the docs site Stop the Hugo process by hitting Ctrl+C. Now we are going to run hugo again, but this time with hugo in watch mode. ``` /path/to/hugo/from/step/1/hugo server --source=./docs --watch > 29 pages created > 0 tags index created > in 27 ms > Web Server is available at http://localhost:1313 > Watching for changes in /Users/spf13/Code/hugo/docs/content > Press ctrl+c to stop ``` Open yourfavorite editorand change one of the source content pages. How about changing this very file to *fix the typo*. How about changing this very file to *fix the typo*. Content files are found in `docs/content/`. Unless otherwise specified, files are located at the same relative location as the url, in our case `docs/content/overview/quickstart.md`. Change and save this file.. Notice what happened in your terminal. ``` > Change detected, rebuilding site > 29 pages created > 0 tags index created > in 26 ms ``` Refresh the browser and observe that the typo is now fixed. Notice how quick that was. Try to refresh the site before it's finished building. I double dare you. Having nearly instant feedback enables you to have your creativity flow without waiting for long builds. Step 4. Have fun The best way to learn something is to play with it. MathJax 支持 /posts/hugo/mathjax%E6%94%AF%E6%8C%81/ Inline Math ``` mathjax {title=Example render = true} abc e^{\pi i}=-1 \frac{3}{2} ``` Display Math ``` mathjax {title=Example render = true} \sum_{i=1}^{n}\int_{0}^{\pi}\log_2{e^n} ``` Using Latex Codeblock ``` latex f(n)= \begin{cases} f(n-1)+f(n-2) & n \ge 3 \\ 1 & n=1,2 \end{cases} ``` ``` latex f(n)= \begin{cases} f(n-1)+f(n-2) & n \ge 3 \\ 1 & n=1,2 \end{cases} ``` 扩展语法支持 /posts/hugo/%E6%89%A9%E5%B1%95%E8%AF%AD%E6%B3%95%E6%94%AF%E6%8C%81/ MkDocs 语法 Hint ::: ``` markdown { title=Example, render=true } !!! note `markdown` text ``` ::: ``` markdown { title=Example, render=true } !!! note Custom Title `markdown` text ``` <!-- --> ::: ``` markdown { title=Example, render=true } ??? note Collapsible `markdown` text ``` ::: ``` markdown { title=Example, render=true } ???+ note Collapsible Open `markdown` text ``` Hint 允许包含和嵌套任意内容。 ``` markdown { title=Example, render=true } ???+ bug ???+ bug ???+ bug Nested bugs. ``` MkDocs 一共支持 12 种 Hint。 ::: !!! note `markdown` text ::: !!! abstract `markdown` text ::: !!! info `markdown` text <!-- --> ::: !!! tip `markdown` text ::: !!! success `markdown` text ::: !!! question `markdown` text <!-- --> ::: !!! warning `markdown` text ::: !!! failure `markdown` text ::: !!! danger `markdown` text <!-- --> ::: !!! bug `markdown` text ::: !!! example `markdown` text ::: !!! quote `markdown` text Columns Columns 用于并排显示某些内容(在较窄的屏幕上会自动取消 Columns 效果)。 通过 HTML 注释 `<!-- -->` 将不同的 Columns 隔开。 ``` markdown { title=Example, render=true } ::: !!! note Top Left `markdown` text ::: !!! note Top Right `markdown` text <!-- --> ::: !!! note Bottom Left `markdown` text ::: !!! note Bottom Right `markdown` text ``` Tabs Tabs 用于呈现选项卡效果,允许包含和嵌套任意内容。 当 Tab 没有内容时,对应的选项卡将不可点击。 ``` markdown { title=Example, render=true } === Disabled === Tab 1 !!! tip This is Tab 1. === Tab 2 !!! warning This is Tab 2. === Tab 3 !!! danger This is Tab 3. ``` Stellar 语法 Inline Note ``` markdown { title=Example, render=true } {% note Title `Markdown` text %} {% note color:red Title `Markdown` text %} <!-- 使用 " " 在标题中呈现空格 --> {% note color:blue Hello World `Markdown` text %} ``` Note 一共支持 12 种颜色。 ::: {% note Default `Markdown` text %} ::: {% note color:red red `Markdown` text %} ::: {% note color:orange orange `Markdown` text %} <!-- --> ::: {% note color:yellow yellow `Markdown` text %} ::: {% note color:green green `Markdown` text %} ::: {% note color:cyan cyan `Markdown` text %} <!-- --> ::: {% note color:blue blue `Markdown` text %} ::: {% note color:purple purple `Markdown` text %} ::: {% note color:light light `Markdown` text %} <!-- --> ::: {% note color:dark dark `Markdown` text %} ::: {% note color:warning warning `Markdown` text %} ::: {% note color:error error `Markdown` text %} Mark Mark 和Note一样支持 12 种颜色。 ``` markdown { title=Example, render=true } {% mark Default %} {% mark color:blue Blue %} {% mark color:green Green %} ``` Tag ``` markdown { title=Example, render=true } {% tag GitHub https://github.com/ %} {% tag color:blue Hexo https://hexo.io/ %} {% tag color:green W3Schools https://www.w3schools.com/ %} ``` Copy ``` markdown { title=Example, render=true } {% copy sudo apt-get upgrade %} {% copy sudo ubuntu-drivers autoinstall %} ``` Radio ``` markdown { title=Example, render=true } {% radio `markdown` text %} {% radio checked:true `markdown` text %} ``` Checkbox ``` markdown { title=Example, render=true } {% checkbox `markdown` text %} {% checkbox checked:true `markdown` text %} {% checkbox symbol:plus color:green checked:true `markdown` text %} {% checkbox symbol:minus color:yellow checked:true `markdown` text %} {% checkbox symbol:times color:red checked:true `markdown` text %} ``` Display Folding ``` markdown { title=Example, render=true } {% folding Title open:true color:blue %} `Markdown` text {% endfolding %} ``` Folding 允许包含和嵌套任意内容 ``` markdown { title=Example, render=true } {% folding Warning color:yellow %} {% folding Dangerous color:orange %} {% folding Prohibited color:red %} `Markdown` text {% endfolding %} {% endfolding %} {% endfolding %} ``` Poetry ``` markdown { title=Example, render=true } {% poetry 独不见 author:唐·沈佺期 footer:诗词节选 %} 卢家少妇郁金堂,海燕双栖玳瑁梁。 **九月寒砧催木叶,十年征戍忆辽阳。** 白狼河北音书断,丹凤城南秋夜长。 谁为含愁独不见,更教明月照流黄? {% endpoetry %} ``` Migrate to Hugo from Jekyll /posts/hugo/migrate-from-jekyll/ Move static content to `static` Jekyll has a rule that any directory not starting with `_` will be copied as-is to the `_site` output. Hugo keeps all static content under `static`. You should therefore move it all there. With Jekyll, something that looked like ▾ <root>/ ▾ images/ logo.png should become ▾ <root>/ ▾ static/ ▾ images/ logo.png Additionally, you'll want any files that should reside at the root (such as `CNAME`) to be moved to `static`. Create your Hugo configuration file Hugo can read your configuration as JSON, YAML or TOML. Hugo supports parameters custom configuration too. Refer to theHugo configuration documentationfor details. Set your configuration publish folder to `_site` The default is for Jekyll to publish to `_site` and for Hugo to publish to `public`. If, like me, you have`_site` mapped to a git submodule on the `gh-pages` branch, you'll want to do one of two alternatives: 1. Change your submodule to point to map `gh-pages` to public instead of `_site` (recommended). git submodule deinit _site git rm _site git submodule add -b gh-pages git@github.com:your-username/your-repo.git public 2. Or, change the Hugo configuration to use `_site` instead of `public`. { .. "publishdir": "_site", .. } Convert Jekyll templates to Hugo templates That's the bulk of the work right here. The documentation is your friend. You should refer toJekyll's template documentationif you need to refresh your memory on how you built your blog andHugo's templateto learn Hugo's way. As a single reference data point, converting my templates forheyitsalex.nettook me no more than a few hours. Convert Jekyll plugins to Hugo shortcodes Jekyll hasplugins; Hugo hasshortcodes. It's fairly trivial to do a port. Implementation As an example, I was using a custom`image_tag`plugin to generate figures with caption when running Jekyll. As I read about shortcodes, I found Hugo had a nice built-in shortcode that does exactly the same thing. Jekyll's plugin: module Jekyll class ImageTag < Liquid::Tag @url = nil @caption = nil @class = nil @link = nil // Patterns IMAGE_URL_WITH_CLASS_AND_CAPTION = IMAGE_URL_WITH_CLASS_AND_CAPTION_AND_LINK = /(\w+)(\s+)((https?:\/\/|\/)(\S+))(\s+)"(.*?)"(\s+)->((https?:\/\/|\/)(\S+))(\s*)/i IMAGE_URL_WITH_CAPTION = /((https?:\/\/|\/)(\S+))(\s+)"(.*?)"/i IMAGE_URL_WITH_CLASS = /(\w+)(\s+)((https?:\/\/|\/)(\S+))/i IMAGE_URL = /((https?:\/\/|\/)(\S+))/i def initialize(tag_name, markup, tokens) super if markup =~ IMAGE_URL_WITH_CLASS_AND_CAPTION_AND_LINK @class = 1 @url = 3 @caption = 7 @link = 9 elsif markup =~ IMAGE_URL_WITH_CLASS_AND_CAPTION @class = 1 @url = 3 @caption = 7 elsif markup =~ IMAGE_URL_WITH_CAPTION @url = 1 @caption = 5 elsif markup =~ IMAGE_URL_WITH_CLASS @class = 1 @url = 3 elsif markup =~ IMAGE_URL @url = 1 end end def render(context) if @class source = "<figure class='{@class}'>" else source = "<figure>" end if @link source += "<a href=\"{@link}\">" end source += "<img src=\"{@url}\">" if @link source += "</a>" end source += "<figcaption>{@caption}</figcaption>" if @caption source += "</figure>" source end end end Liquid::Template.register_tag('image', Jekyll::ImageTag) is written as this Hugo shortcode: <!-- image --> <figure class=""> <a href=""> <img src="" alt="" /> </a> <figcaption> <p> <a href=""> </a> </p> </figcaption> </figure> <!-- image --> Usage I simply changed: {% image full http://farm5.staticflickr.com/4136/4829260124_57712e570a_o_d.jpg "One of my favorite touristy-type photos. I secretly waited for the good light while we were "having fun" and took this. Only regret: a stupid pole in the top-left corner of the frame I had to clumsily get rid of at post-processing." ->http://www.flickr.com/photos/alexnormand/4829260124/in/set-72157624547713078/ %} to this (this example uses a slightly extended version named `fig`, different than the built-in `figure`): As a bonus, the shortcode named parameters are, arguably, more readable. Finishing touches Fix content Depending on the amount of customization that was done with each post with Jekyll, this step will require more or less effort. There are no hard and fast rules here except that `hugo server --watch` is your friend. Test your changes and fix errors as needed. Clean up You'll want to remove the Jekyll configuration at this point. If you have anything else that isn't used, delete it. A practical example in a diffHey, it's Alexwas migrated in less than a _father-with-kids day_ from Jekyll to Hugo. You can see all the changes (and screw-ups) by looking at thisdiff.
text /docs/example/folder_1/text/ h2 h3 h4