diff --git a/package.json b/package.json index c4bbd5cd96..9310cb4e97 100644 --- a/package.json +++ b/package.json @@ -8,6 +8,7 @@ "scripts": { "build": "hexo generate", "eslint": "eslint .", + "format:md": "prettier --write */**/docs/*.md */**/api/*.md", "prepare": "husky" }, "dependencies": { @@ -32,13 +33,15 @@ "eslint-config-hexo": "^5.0.0", "husky": "^9.0.6", "imagemin-lint-staged": "^0.5.1", - "lint-staged": "^15.2.0" + "lint-staged": "^15.2.0", + "prettier": "3.2.5" }, "lint-staged": { "*.{png,jpeg,jpg,gif,svg}": [ "imagemin-lint-staged" ], - "*.js": "eslint --fix" + "*.js": "eslint --fix", + "*.md": "prettier --write" }, "engines": { "node": ">=14" diff --git a/source/api/box.md b/source/api/box.md index 3cf4ebe3d9..17f9b22d6a 100644 --- a/source/api/box.md +++ b/source/api/box.md @@ -1,18 +1,19 @@ --- title: Box --- + Box is a container used for processing files in a specified folder. Hexo uses two different boxes: `hexo.source` and `hexo.theme`. The former is used to process the `source` folder and the latter to process the `theme` folder. ## Load Files Box provides two methods for loading files: `process` and `watch`. `process` loads all files in the folder. `watch` does the same, but also starts watching for file changes. -``` js -box.process().then(function(){ +```js +box.process().then(function () { // ... }); -box.watch().then(function(){ +box.watch().then(function () { // You can call box.unwatch() later to stop watching. }); ``` @@ -21,7 +22,7 @@ box.watch().then(function(){ Box provides many ways for path matching. You can use a regular expression, a function or an Express-style pattern string. For example: -``` plain +```plain posts/:id => posts/89 posts/*path => posts/2015/title ``` @@ -32,30 +33,30 @@ See [util.Pattern] for more info. A processor is an essential element of Box and is used to process files. You can use path matching as described above to restrict what exactly the processor should process. Register a new processor with the `addProcessor` method. -``` js -box.addProcessor('posts/:id', function(file){ +```js +box.addProcessor("posts/:id", function (file) { // }); ``` Box passes the content of matched files to processors. This information can then be read straight from the `file` argument in the callback: -Attribute | Description ---- | --- -`source` | Full path of the file -`path` | Relative path to the box of the file -`type` | File type. The value can be `create`, `update`, `skip`, `delete`. -`params` | The information from path matching. +| Attribute | Description | +| --------- | ----------------------------------------------------------------- | +| `source` | Full path of the file | +| `path` | Relative path to the box of the file | +| `type` | File type. The value can be `create`, `update`, `skip`, `delete`. | +| `params` | The information from path matching. | Box also provides some methods so you don't have to do file IO by yourself. -Method | Description ---- | --- -`read` | Read a file -`readSync` | Read a file synchronously -`stat` | Read the status of a file -`statSync` | Read the status of a file synchronously -`render` | Render a file -`renderSync` | Render a file synchronously +| Method | Description | +| ------------ | --------------------------------------- | +| `read` | Read a file | +| `readSync` | Read a file synchronously | +| `stat` | Read the status of a file | +| `statSync` | Read the status of a file synchronously | +| `render` | Render a file | +| `renderSync` | Render a file synchronously | [util.Pattern]: https://github.com/hexojs/hexo-util#patternrule diff --git a/source/api/console.md b/source/api/console.md index 09b05879f1..f03bea2a85 100644 --- a/source/api/console.md +++ b/source/api/console.md @@ -1,21 +1,22 @@ --- title: Console --- + The console forms the bridge between Hexo and its users. It registers and describes the available console commands. ## Synopsis -``` js -hexo.extend.console.register(name, desc, options, function(args){ +```js +hexo.extend.console.register(name, desc, options, function (args) { // ... }); ``` -Argument | Description ---- | --- -`name` | Name -`desc` | Description -`options`| Options +| Argument | Description | +| --------- | ----------- | +| `name` | Name | +| `desc` | Description | +| `options` | Options | An argument `args` will be passed into the function. This is the argument that users type into the terminal. It's parsed by [Minimist]. @@ -25,8 +26,10 @@ An argument `args` will be passed into the function. This is the argument that u The usage of a console command. For example: -``` js -{usage: '[layout] '} +```js +{ + usage: "[layout] <title>"; +} // hexo new [layout] <title> ``` @@ -34,12 +37,12 @@ The usage of a console command. For example: The description of each argument of a console command. For example: -``` js +```js { arguments: [ - {name: 'layout', desc: 'Post layout'}, - {name: 'title', desc: 'Post title'} - ] + { name: "layout", desc: "Post layout" }, + { name: "title", desc: "Post title" }, + ]; } ``` @@ -47,11 +50,9 @@ The description of each argument of a console command. For example: The description of each option of a console command. For example: -``` js +```js { - options: [ - {name: '-r, --replace', desc: 'Replace existing files'} - ] + options: [{ name: "-r, --replace", desc: "Replace existing files" }]; } ``` @@ -61,10 +62,14 @@ More detailed information about a console command. ## Example -``` js -hexo.extend.console.register('config', 'Display configuration', function(args){ - console.log(hexo.config); -}); +```js +hexo.extend.console.register( + "config", + "Display configuration", + function (args) { + console.log(hexo.config); + }, +); ``` [Minimist]: https://github.com/minimistjs/minimist diff --git a/source/api/deployer.md b/source/api/deployer.md index 0ba8868f69..c26df36fdd 100644 --- a/source/api/deployer.md +++ b/source/api/deployer.md @@ -1,12 +1,13 @@ --- title: Deployer --- + A deployer helps users quickly deploy their site to a remote server without complicated commands. ## Synopsis -``` js -hexo.extend.deployer.register(name, function(args){ +```js +hexo.extend.deployer.register(name, function (args) { // ... }); ``` diff --git a/source/api/events.md b/source/api/events.md index 21dc185355..4a72f43dbc 100644 --- a/source/api/events.md +++ b/source/api/events.md @@ -1,6 +1,7 @@ --- title: Events --- + Hexo inherits from [EventEmitter]. Use the `on` method to listen for events emitted by Hexo, and use the `emit` method to emit events. For more information, refer to the Node.js API documentation. ### deployBefore @@ -27,16 +28,16 @@ Emitted after generation finishes. Emitted after a new post has been created. This event returns the post data: -``` js -hexo.on('new', function(post){ +```js +hexo.on("new", function (post) { // }); ``` -Data | Description ---- | --- -`post.path` | Full path of the post file -`post.content` | Content of the post file +| Data | Description | +| -------------- | -------------------------- | +| `post.path` | Full path of the post file | +| `post.content` | Content of the post file | ### processBefore diff --git a/source/api/filter.md b/source/api/filter.md index 8f948d3b60..acd44c6a1c 100644 --- a/source/api/filter.md +++ b/source/api/filter.md @@ -1,11 +1,12 @@ --- title: Filter --- + A filter is used to modify some specified data. Hexo passes data to filters in sequence and the filters then modify the data one after the other. This concept was borrowed from [WordPress](http://codex.wordpress.org/Plugin_API#Filters). ## Synopsis -``` js +```js hexo.extend.filter.register(type, function() { // User configuration const { config } = this; @@ -22,69 +23,69 @@ You can define the `priority`. Lower `priority` means that it will be executed f ## Execute Filters -``` js +```js hexo.extend.filter.exec(type, data, options); hexo.extend.filter.execSync(type, data, options); ``` -Option | Description ---- | --- -`context` | Context -`args` | Arguments. This must be an array. +| Option | Description | +| --------- | --------------------------------- | +| `context` | Context | +| `args` | Arguments. This must be an array. | The first argument passed into each filter is `data`. The `data` passed into the next filter can be modified by returning a new value. If nothing is returned, the data remains unmodified. You can even use `args` to specify other arguments in filters. For example: -``` js -hexo.extend.filter.register('test', function(data, arg1, arg2){ +```js +hexo.extend.filter.register("test", function (data, arg1, arg2) { // data === 'some data' // arg1 === 'foo' // arg2 === 'bar' - return 'something'; + return "something"; }); -hexo.extend.filter.register('test', function(data, arg1, arg2){ +hexo.extend.filter.register("test", function (data, arg1, arg2) { // data === 'something' }); -hexo.extend.filter.exec('test', 'some data', { - args: ['foo', 'bar'] +hexo.extend.filter.exec("test", "some data", { + args: ["foo", "bar"], }); ``` You can also use the following methods to execute filters: -``` js +```js hexo.execFilter(type, data, options); hexo.execFilterSync(type, data, options); ``` ## Unregister Filters -``` js +```js hexo.extend.filter.unregister(type, filter); ``` **Example** -``` js +```js // Unregister a filter which is registered with named function const filterFn = (data) => { - data = 'something'; + data = "something"; return data; }; -hexo.extend.filter.register('example', filterFn); +hexo.extend.filter.register("example", filterFn); -hexo.extend.filter.unregister('example', filterFn); +hexo.extend.filter.unregister("example", filterFn); ``` -``` js +```js // Unregister a filter which is registered with commonjs module -hexo.extend.filter.register('example', require('path/to/filter')); +hexo.extend.filter.register("example", require("path/to/filter")); -hexo.extend.filter.unregister('example', require('path/to/filter')); +hexo.extend.filter.unregister("example", require("path/to/filter")); ``` ## Filter List @@ -97,8 +98,8 @@ Executed before a post is rendered. Refer to [post rendering](posts.html#Render) For example, to transform the title to lower case: -``` js -hexo.extend.filter.register('before_post_render', function(data){ +```js +hexo.extend.filter.register("before_post_render", function (data) { data.title = data.title.toLowerCase(); return data; }); @@ -110,9 +111,12 @@ Executed after a post is rendered. Refer to [post rendering](posts.html#Render) For example, to replace `@username` with a link to a Twitter profile: -``` js -hexo.extend.filter.register('after_post_render', function(data){ - data.content = data.content.replace(/@(\d+)/, '<a href="http://twitter.com/$1">#$1</a>'); +```js +hexo.extend.filter.register("after_post_render", function (data) { + data.content = data.content.replace( + /@(\d+)/, + '<a href="http://twitter.com/$1">#$1</a>', + ); return data; }); ``` @@ -121,8 +125,8 @@ hexo.extend.filter.register('after_post_render', function(data){ Executed before Hexo is about to exit -- this will run right after `hexo.exit` is called. -``` js -hexo.extend.filter.register('before_exit', function(){ +```js +hexo.extend.filter.register("before_exit", function () { // ... }); ``` @@ -131,8 +135,8 @@ hexo.extend.filter.register('before_exit', function(){ Executed before generation begins. -``` js -hexo.extend.filter.register('before_generate', function(){ +```js +hexo.extend.filter.register("before_generate", function () { // ... }); ``` @@ -141,8 +145,8 @@ hexo.extend.filter.register('before_generate', function(){ Executed after generation finishes. -``` js -hexo.extend.filter.register('after_generate', function(){ +```js +hexo.extend.filter.register("after_generate", function () { // ... }); ``` @@ -153,8 +157,8 @@ Modify [local variables](../docs/variables.html) in templates. For example, to add the current time to the local variables of templates: -``` js -hexo.extend.filter.register('template_locals', function(locals){ +```js +hexo.extend.filter.register("template_locals", function (locals) { locals.now = Date.now(); return locals; }); @@ -164,8 +168,8 @@ hexo.extend.filter.register('template_locals', function(locals){ Executed after Hexo is initialized -- this will run right after `hexo.init` completes. -``` js -hexo.extend.filter.register('after_init', function(){ +```js +hexo.extend.filter.register("after_init", function () { // ... }); ``` @@ -174,8 +178,8 @@ hexo.extend.filter.register('after_init', function(){ Executed when creating a post to determine the path of new posts. -``` js -hexo.extend.filter.register('new_post_path', function(data, replace){ +```js +hexo.extend.filter.register("new_post_path", function (data, replace) { // ... }); ``` @@ -184,8 +188,8 @@ hexo.extend.filter.register('new_post_path', function(data, replace){ Used to determine the permalink of posts. -``` js -hexo.extend.filter.register('post_permalink', function(data){ +```js +hexo.extend.filter.register("post_permalink", function (data) { // ... }); ``` @@ -198,8 +202,8 @@ Executed after rendering finishes. You can see [rendering](rendering.html#after_ Executed after generated files and cache are removed with `hexo clean` command. -``` js -hexo.extend.filter.register('after_clean', function(){ +```js +hexo.extend.filter.register("after_clean", function () { // remove some other temporary files }); ``` @@ -210,10 +214,10 @@ Add middleware to the server. `app` is a [Connect] instance. For example, to add `X-Powered-By: Hexo` to the response header: -``` js -hexo.extend.filter.register('server_middleware', function(app){ - app.use(function(req, res, next){ - res.setHeader('X-Powered-By', 'Hexo'); +```js +hexo.extend.filter.register("server_middleware", function (app) { + app.use(function (req, res, next) { + res.setHeader("X-Powered-By", "Hexo"); next(); }); }); diff --git a/source/api/generator.md b/source/api/generator.md index 97c067f252..c7062f0986 100644 --- a/source/api/generator.md +++ b/source/api/generator.md @@ -1,12 +1,13 @@ --- title: Generator --- + A generator builds routes based on processed files. ## Synopsis -``` js -hexo.extend.generator.register(name, function(locals){ +```js +hexo.extend.generator.register(name, function (locals) { // ... }); ``` @@ -15,27 +16,27 @@ A `locals` argument will get passed into the function, containing the [site vari ## Update Routes -``` js -hexo.extend.generator.register('test', function(locals){ +```js +hexo.extend.generator.register("test", function (locals) { // Object return { - path: 'foo', - data: 'foo' + path: "foo", + data: "foo", }; // Array return [ - {path: 'foo', data: 'foo'}, - {path: 'bar', data: 'bar'} + { path: "foo", data: "foo" }, + { path: "bar", data: "bar" }, ]; }); ``` -Attribute | Description ---- | --- -`path` | Path not including the prefixing `/`. -`data` | Data -`layout` | Layout. Specify the layouts for rendering. The value can be a string or an array. If it's ignored then the route will return `data` directly. +| Attribute | Description | +| --------- | --------------------------------------------------------------------------------------------------------------------------------------------- | +| `path` | Path not including the prefixing `/`. | +| `data` | Data | +| `layout` | Layout. Specify the layouts for rendering. The value can be a string or an array. If it's ignored then the route will return `data` directly. | When the source files are updated, Hexo will execute all generators and rebuild the routes. **Please return the data and do not access the router directly.** @@ -47,13 +48,13 @@ Create an archive page at `archives/index.html`. We pass all posts as data to th Next, set the `layout` attribute to render with the theme templates. We're setting two layouts in this example: if the `archive` layout doesn't exist, the `index` layout will be used instead. -``` js -hexo.extend.generator.register('archive', function(locals){ +```js +hexo.extend.generator.register("archive", function (locals) { return { - path: 'archives/index.html', + path: "archives/index.html", data: locals, - layout: ['archive', 'index'] - } + layout: ["archive", "index"], + }; }); ``` @@ -61,15 +62,15 @@ hexo.extend.generator.register('archive', function(locals){ You can use the convenient official tool [hexo-pagination] to easily build archive pages with pagination. -``` js -var pagination = require('hexo-pagination'); +```js +var pagination = require("hexo-pagination"); -hexo.extend.generator.register('archive', function(locals){ +hexo.extend.generator.register("archive", function (locals) { // hexo-pagination makes an index.html for the /archives route - return pagination('archives', locals.posts, { + return pagination("archives", locals.posts, { perPage: 10, - layout: ['archive', 'index'], - data: {} + layout: ["archive", "index"], + data: {}, }); }); ``` @@ -78,13 +79,13 @@ hexo.extend.generator.register('archive', function(locals){ Iterate over all posts in `locals.posts` and create routes for all the posts. -``` js -hexo.extend.generator.register('post', function(locals){ - return locals.posts.map(function(post){ +```js +hexo.extend.generator.register("post", function (locals) { + return locals.posts.map(function (post) { return { path: post.path, data: post, - layout: 'post' + layout: "post", }; }); }); @@ -94,15 +95,15 @@ hexo.extend.generator.register('post', function(locals){ This time we don't return the data explicitly but instead set `data` to a function so the route will build `fs.ReadStream` only when needed. -``` js -var fs = require('hexo-fs'); +```js +var fs = require("hexo-fs"); -hexo.extend.generator.register('asset', function(locals){ +hexo.extend.generator.register("asset", function (locals) { return { - path: 'file.txt', - data: function(){ - return fs.createReadStream('path/to/file.txt') - } + path: "file.txt", + data: function () { + return fs.createReadStream("path/to/file.txt"); + }, }; }); ``` diff --git a/source/api/helper.md b/source/api/helper.md index 104762b9cd..76a72e8bcd 100644 --- a/source/api/helper.md +++ b/source/api/helper.md @@ -1,27 +1,28 @@ --- title: Helper --- + A helper makes it easy to quickly add snippets to your templates. We recommend using helpers instead of templates when you're dealing with more complicated code. Helpers can not be accessed from `source` files. ## Synopsis -``` js -hexo.extend.helper.register(name, function(){ +```js +hexo.extend.helper.register(name, function () { // ... }); ``` ## Example -``` js -hexo.extend.helper.register('js', function(path){ +```js +hexo.extend.helper.register("js", function (path) { return '<script src="' + path + '"></script>'; }); ``` -``` js +```js <%- js('script.js') %> // <script src="script.js"></script> ``` @@ -36,8 +37,8 @@ Place it under `scripts/` or `themes/<yourtheme>/scripts/` folder. All helpers are executed in the same context. For example, to use [`url_for()`](/docs/helpers#url-for) inside a custom helper: -``` js -hexo.extend.helper.register('lorem', function(path) { +```js +hexo.extend.helper.register("lorem", function (path) { return '<script src="' + this.url_for(path) + '"></script>'; }); ``` @@ -46,6 +47,6 @@ hexo.extend.helper.register('lorem', function(path) { `hexo.extend.helper.get` will return the helper function, but it needs to have hexo as its context, so: -``` js -const url_for = hexo.extend.helper.get('url_for').bind(hexo); +```js +const url_for = hexo.extend.helper.get("url_for").bind(hexo); ``` diff --git a/source/api/index.md b/source/api/index.md index 0b4b67f4ac..e6f3445454 100644 --- a/source/api/index.md +++ b/source/api/index.md @@ -1,6 +1,7 @@ --- title: API --- + This documentation provides more detailed information about the API and will be particularly helpful for people who want to modify the Hexo source code or write new plugins. If you are interested in more basic usage of Hexo, please refer to the [docs](../docs) instead. Please note that this documentation is only valid for Hexo 3 and above. @@ -9,22 +10,22 @@ Please note that this documentation is only valid for Hexo 3 and above. First, we have to create a Hexo instance. A new instance takes two arguments: the root directory of the website, `base_dir`, and an object containing the initialization options. Next, we initialize this instance by calling the `init` method on it, which will then cause Hexo to load its configuration and plugins. -``` js -var Hexo = require('hexo'); +```js +var Hexo = require("hexo"); var hexo = new Hexo(process.cwd(), {}); -hexo.init().then(function(){ +hexo.init().then(function () { // ... }); ``` -Option | Description | Default ---- | --- | --- -`debug` | Enable debug mode. Display debug messages in the terminal and save `debug.log` in the root directory. | `false` -`safe` | Enable safe mode. Don't load any plugins. | `false` -`silent` | Enable silent mode. Don't display any messages in the terminal. | `false` -`config` | Specify the path of the configuration file. | `_config.yml` -`draft` / `drafts`| Enable to add drafts to the posts list.<br> example: when you use `hexo.locals.get('posts')` | `render_drafts` of _config.yml +| Option | Description | Default | +| ------------------ | ----------------------------------------------------------------------------------------------------- | ------------------------------- | +| `debug` | Enable debug mode. Display debug messages in the terminal and save `debug.log` in the root directory. | `false` | +| `safe` | Enable safe mode. Don't load any plugins. | `false` | +| `silent` | Enable silent mode. Don't display any messages in the terminal. | `false` | +| `config` | Specify the path of the configuration file. | `_config.yml` | +| `draft` / `drafts` | Enable to add drafts to the posts list.<br> example: when you use `hexo.locals.get('posts')` | `render_drafts` of \_config.yml | ## Load Files @@ -32,12 +33,12 @@ Hexo provides two methods for loading files: `load` and `watch`. `load` is used Both methods will load the list of files and pass them to the corresponding processors. After all files have been processed, they will call upon the generators to create the routes. -``` js -hexo.load().then(function(){ +```js +hexo.load().then(function () { // ... }); -hexo.watch().then(function(){ +hexo.watch().then(function () { // You can call hexo.unwatch() later to stop watching. }); ``` @@ -46,26 +47,29 @@ hexo.watch().then(function(){ Any console command can be called explicitly using the `call` method on the Hexo instance. Such a call takes two arguments: the name of the console command, and an options argument. Different options are available for the different console commands. -``` js -hexo.call('generate', {}).then(function(){ +```js +hexo.call("generate", {}).then(function () { // ... }); ``` -``` js -hexo.call('list', { _: ['post'] }).then(function() { +```js +hexo.call("list", { _: ["post"] }).then(function () { // ... -}) +}); ``` ## Exit You should call the `exit` method upon successful or unsuccessful completion of a console command. This allows Hexo to exit gracefully and finish up important things such as saving the database. -``` js -hexo.call('generate').then(function(){ - return hexo.exit(); -}).catch(function(err){ - return hexo.exit(err); -}); +```js +hexo + .call("generate") + .then(function () { + return hexo.exit(); + }) + .catch(function (err) { + return hexo.exit(err); + }); ``` diff --git a/source/api/injector.md b/source/api/injector.md index 80d43a2085..a1200bf9d7 100644 --- a/source/api/injector.md +++ b/source/api/injector.md @@ -7,7 +7,7 @@ An injector is used to add static code snippet to the `<head>` or/and `<body>` o ## Synopsis ```js -hexo.extend.injector.register(entry, value, to) +hexo.extend.injector.register(entry, value, to); ``` ### entry `<string>` @@ -40,24 +40,34 @@ Which page will code snippets being injected. - `tag`: Only inject to tag pages (which has `is_tag()` helper being `true`) - Custom layout name could be used as well, see [Writing - Layout](/docs/writing#Layout). ----- +--- There are other internal functions, see [hexojs/hexo#4049](https://github.com/hexojs/hexo/pull/4049) for more details. ## Example ```js -const css = hexo.extend.helper.get('css').bind(hexo); -const js = hexo.extend.helper.get('js').bind(hexo); - -hexo.extend.injector.register('head_end', () => { - return css('https://cdn.jsdelivr.net/npm/aplayer@1.10.1/dist/APlayer.min.css'); -}, 'music'); - -hexo.extend.injector.register('body_end', '<script src="https://cdn.jsdelivr.net/npm/aplayer@1.10.1/dist/APlayer.min.js">', 'music'); - -hexo.extend.injector.register('body_end', () => { - return js('/js/jquery.js'); +const css = hexo.extend.helper.get("css").bind(hexo); +const js = hexo.extend.helper.get("js").bind(hexo); + +hexo.extend.injector.register( + "head_end", + () => { + return css( + "https://cdn.jsdelivr.net/npm/aplayer@1.10.1/dist/APlayer.min.css", + ); + }, + "music", +); + +hexo.extend.injector.register( + "body_end", + '<script src="https://cdn.jsdelivr.net/npm/aplayer@1.10.1/dist/APlayer.min.js">', + "music", +); + +hexo.extend.injector.register("body_end", () => { + return js("/js/jquery.js"); }); ``` @@ -69,10 +79,10 @@ Use any of the following options: 1. -``` js -const css = hexo.extend.helper.get('css').bind(hexo); +```js +const css = hexo.extend.helper.get("css").bind(hexo); -hexo.extend.injector.register('head_end', () => { +hexo.extend.injector.register("head_end", () => { const { cssPath } = hexo.config.fooPlugin; return css(cssPath); }); @@ -80,23 +90,23 @@ hexo.extend.injector.register('head_end', () => { 2. -``` js index.js +```js index.js /* global hexo */ -hexo.extend.injector.register('head_end', require('./lib/inject').bind(hexo)) +hexo.extend.injector.register("head_end", require("./lib/inject").bind(hexo)); ``` -``` js lib/inject.js +```js lib/inject.js module.exports = function () { - const css = this.extend.helper.get('css'); + const css = this.extend.helper.get("css"); const { cssPath } = this.config.fooPlugin; return css(cssPath); -} +}; ``` -``` js lib/inject.js +```js lib/inject.js function injectFn() { - const css = this.extend.helper.get('css'); + const css = this.extend.helper.get("css"); const { cssPath } = this.config.fooPlugin; return css(cssPath); } @@ -106,23 +116,23 @@ module.exports = injectFn; 3. -``` js index.js +```js index.js /* global hexo */ -hexo.extend.injector.register('head_end', require('./lib/inject')(hexo)) +hexo.extend.injector.register("head_end", require("./lib/inject")(hexo)); ``` -``` js lib/inject.js +```js lib/inject.js module.exports = (hexo) => () => { - const css = hexo.extend.helper.get('css').bind(hexo); + const css = hexo.extend.helper.get("css").bind(hexo); const { cssPath } = hexo.config.fooPlugin; return css(cssPath); }; ``` -``` js lib/inject.js +```js lib/inject.js const injectFn = (hexo) => { - const css = hexo.extend.helper.get('css').bind(hexo); + const css = hexo.extend.helper.get("css").bind(hexo); const { cssPath } = hexo.config.fooPlugin; return css(cssPath); }; diff --git a/source/api/locals.md b/source/api/locals.md index 1fabd68974..2b2e54a848 100644 --- a/source/api/locals.md +++ b/source/api/locals.md @@ -1,26 +1,27 @@ --- title: Local Variables --- + Local variables are used for template rendering, which is the `site` variable in templates. ## Default Variables -Variable | Description ---- | --- -`posts` | All posts -`pages` | All pages -`categories` | All categories -`tags` | All tags +| Variable | Description | +| ------------ | -------------- | +| `posts` | All posts | +| `pages` | All pages | +| `categories` | All categories | +| `tags` | All tags | ## Get a Variable -``` js -hexo.locals.get('posts') +```js +hexo.locals.get("posts"); ``` ## Set a Variable -``` js +```js hexo.locals.set('posts', function(){ return ... }); @@ -28,18 +29,18 @@ hexo.locals.set('posts', function(){ ## Remove a Variable -``` js -hexo.locals.remove('posts'); +```js +hexo.locals.remove("posts"); ``` ## Get All Variable -``` js +```js hexo.locals.toObject(); ``` ## Invalidate the cache -``` js +```js hexo.locals.invalidate(); ``` diff --git a/source/api/migrator.md b/source/api/migrator.md index a29698e5e0..2f57a842c1 100644 --- a/source/api/migrator.md +++ b/source/api/migrator.md @@ -1,12 +1,13 @@ --- title: Migrator --- + A migrator helps users migrate from other systems to Hexo. ## Synopsis -``` js -hexo.extend.migrator.register(name, function(args){ +```js +hexo.extend.migrator.register(name, function (args) { // ... }); ``` diff --git a/source/api/posts.md b/source/api/posts.md index c86554be1e..5cb39f2d73 100644 --- a/source/api/posts.md +++ b/source/api/posts.md @@ -1,55 +1,56 @@ --- title: Posts --- + ## Create a Post -``` js +```js hexo.post.create(data, replace); ``` -Argument | Description ---- | --- -`data` | Data -`replace` | Replace existing files +| Argument | Description | +| --------- | ---------------------- | +| `data` | Data | +| `replace` | Replace existing files | The attributes of a post can be defined in `data`. The table below is not exhaustive. Additional attributes may be appended to the front-matter. -Data | Description ---- | --- -`title` | Title -`slug` | URL -`layout` | Layout. Defaults to the `default_layout` setting. -`path` | Path. Hexo builds the post path based on the `new_post_path` setting by default. -`date` | Date. Defaults to the current date. +| Data | Description | +| -------- | -------------------------------------------------------------------------------- | +| `title` | Title | +| `slug` | URL | +| `layout` | Layout. Defaults to the `default_layout` setting. | +| `path` | Path. Hexo builds the post path based on the `new_post_path` setting by default. | +| `date` | Date. Defaults to the current date. | ## Publish a Draft -``` js +```js hexo.post.publish(data, replace); ``` -Argument | Description ---- | --- -`data` | Data -`replace` | Replace existing files +| Argument | Description | +| --------- | ---------------------- | +| `data` | Data | +| `replace` | Replace existing files | The attributes of a post can be defined in `data`. The table below is not exhaustive. Additional attributes may be appended to the front-matter. -Data | Description ---- | --- -`slug` | File name (Required) -`layout` | Layout. Defaults to the `default_layout` setting. +| Data | Description | +| -------- | ------------------------------------------------- | +| `slug` | File name (Required) | +| `layout` | Layout. Defaults to the `default_layout` setting. | ## Render -``` js +```js hexo.post.render(source, data); ``` -Argument | Description ---- | --- -`source` | Full path of a file (Optional) -`data` | Data +| Argument | Description | +| -------- | ------------------------------ | +| `source` | Full path of a file (Optional) | +| `data` | Data | The data must contain the `content` attribute. If not, Hexo will try to read the original file. The execution steps of this function are as follows: @@ -59,4 +60,3 @@ The data must contain the `content` attribute. If not, Hexo will try to read the - Execute `after_post_render` filters [Nunjucks]: https://mozilla.github.io/nunjucks/ - diff --git a/source/api/processor.md b/source/api/processor.md index f1e5c0c2a3..52e91f8d07 100644 --- a/source/api/processor.md +++ b/source/api/processor.md @@ -1,13 +1,14 @@ --- title: Processor --- + A processor is used to process source files in the `source` folder. ## Synopsis -``` js -hexo.extend.processor.register(rule, function(file){ - // ... +```js +hexo.extend.processor.register(rule, function (file) { + // ... }); ``` diff --git a/source/api/renderer.md b/source/api/renderer.md index 7bad410c17..916a2c5030 100644 --- a/source/api/renderer.md +++ b/source/api/renderer.md @@ -1,71 +1,86 @@ --- title: Renderer --- + A renderer is used to render content. ## Synopsis -``` js -hexo.extend.renderer.register(name, output, function(data, options){ - // ... -}, sync); +```js +hexo.extend.renderer.register( + name, + output, + function (data, options) { + // ... + }, + sync, +); ``` -Argument | Description ---- | --- -`name` | Input filename extension (lower case, without leading `.`) -`output` | Output filename extension (lower case, without leading `.`) -`sync` | Sync mode +| Argument | Description | +| -------- | ----------------------------------------------------------- | +| `name` | Input filename extension (lower case, without leading `.`) | +| `output` | Output filename extension (lower case, without leading `.`) | +| `sync` | Sync mode | Three arguments will be passed into the render function: -Argument | Description ---- | --- -`data` | Include two attributes: file path `path` and file content `text`. `path` won't necessarily exist. -`option` | Options -`callback` | Callback function of two parameters `err`, `value`. +| Argument | Description | +| ---------- | ------------------------------------------------------------------------------------------------- | +| `data` | Include two attributes: file path `path` and file content `text`. `path` won't necessarily exist. | +| `option` | Options | +| `callback` | Callback function of two parameters `err`, `value`. | ## Example ### Async Mode -``` js -var stylus = require('stylus'); +```js +var stylus = require("stylus"); // Callback -hexo.extend.renderer.register('styl', 'css', function(data, options, callback){ - stylus(data.text).set('filename', data.path).render(callback); -}); +hexo.extend.renderer.register( + "styl", + "css", + function (data, options, callback) { + stylus(data.text).set("filename", data.path).render(callback); + }, +); // Promise -hexo.extend.renderer.register('styl', 'css', function(data, options){ - return new Promise(function(resolve, reject){ - resolve('test'); +hexo.extend.renderer.register("styl", "css", function (data, options) { + return new Promise(function (resolve, reject) { + resolve("test"); }); }); ``` ### Sync Mode -``` js -var ejs = require('ejs'); - -hexo.extend.renderer.register('ejs', 'html', function(data, options){ - options.filename = data.path; - return ejs.render(data.text, options); -}, true); +```js +var ejs = require("ejs"); + +hexo.extend.renderer.register( + "ejs", + "html", + function (data, options) { + options.filename = data.path; + return ejs.render(data.text, options); + }, + true, +); ``` ### Disable Nunjucks tags Nunjucks tags `{{ }}` or `{% %}` (utilized by [tag plugin](/docs/tag-plugins)) are processed by default, to disable: -``` js +```js function lessFn(data, options) { // do something } -lessFn.disableNunjucks = true +lessFn.disableNunjucks = true; -hexo.extend.renderer.register('less', 'css', lessFn); +hexo.extend.renderer.register("less", "css", lessFn); ``` diff --git a/source/api/rendering.md b/source/api/rendering.md index 64d87644b3..30a5b3ee20 100644 --- a/source/api/rendering.md +++ b/source/api/rendering.md @@ -1,14 +1,15 @@ --- title: Rendering --- + There are two methods for rendering files or strings in Hexo: the asynchronous `hexo.render.render` method and the synchronous `hexo.render.renderSync` method. Unsurprisingly, the two methods are very similar so only the asynchronous `hexo.render.render` will be further discussed in the below paragraphs. ## Render a String When rendering a string, you must specify an `engine` to let Hexo know which rendering engine it should use. -``` js -hexo.render.render({text: 'example', engine: 'swig'}).then(function(result){ +```js +hexo.render.render({ text: "example", engine: "swig" }).then(function (result) { // ... }); ``` @@ -17,8 +18,8 @@ hexo.render.render({text: 'example', engine: 'swig'}).then(function(result){ When rendering a file, it's not necessary to specify an `engine` because Hexo will detect the relevant rendering engine automatically based on the extension of the file. Of course, you are also allowed to explicitly define the `engine`. -``` js -hexo.render.render({path: 'path/to/file.swig'}).then(function(result){ +```js +hexo.render.render({ path: "path/to/file.swig" }).then(function (result) { // ... }); ``` @@ -27,8 +28,8 @@ hexo.render.render({path: 'path/to/file.swig'}).then(function(result){ You can pass in an options object as the second argument. -``` js -hexo.render.render({text: ''}, {foo: 'foo'}).then(function(result){ +```js +hexo.render.render({ text: "" }, { foo: "foo" }).then(function (result) { // ... }); ``` @@ -37,10 +38,10 @@ hexo.render.render({text: ''}, {foo: 'foo'}).then(function(result){ When rendering is complete, Hexo will execute the corresponding `after_render` filters. For example, we can use this feature to implement a JavaScript minifier. -``` js -var UglifyJS = require('uglify-js'); +```js +var UglifyJS = require("uglify-js"); -hexo.extend.filter.register('after_render:js', function(str, data){ +hexo.extend.filter.register("after_render:js", function (str, data) { var result = UglifyJS.minify(str); return result.code; }); @@ -50,30 +51,30 @@ hexo.extend.filter.register('after_render:js', function(str, data){ You can use the `isRenderable` or `isRenderableSync` method to check whether a file path is renderable. Only when a corresponding renderer has been registered will this method return true. -``` js -hexo.render.isRenderable('layout.swig') // true -hexo.render.isRenderable('image.png') // false +```js +hexo.render.isRenderable("layout.swig"); // true +hexo.render.isRenderable("image.png"); // false ``` ## Get the Output Extension Use the `getOutput` method to get the extension of the rendered output. If a file is not renderable, the method will return an empty string. -``` js -hexo.render.getOutput('layout.swig') // html -hexo.render.getOutput('image.png') // ''' +```js +hexo.render.getOutput("layout.swig"); // html +hexo.render.getOutput("image.png"); // ''' ``` ## Disable Nunjucks tags If you are not using a [tag plugin](/docs/tag-plugins) and want to use `{{ }}` or `{% %}` in your post without using content [escaping](/docs/troubleshooting#Escape-Contents), you can disable processing of Nunjucks tag in existing renderer by: -``` js +```js // following example only applies to '.md' file extension // you may need to cover other extensions, e.g. '.markdown', '.mkd' -const renderer = hexo.render.renderer.get('md') +const renderer = hexo.render.renderer.get("md"); if (renderer) { - renderer.disableNunjucks = true - hexo.extend.renderer.register('md', 'html', renderer) + renderer.disableNunjucks = true; + hexo.extend.renderer.register("md", "html", renderer); } ``` diff --git a/source/api/router.md b/source/api/router.md index 5e745e383c..e4f648762e 100644 --- a/source/api/router.md +++ b/source/api/router.md @@ -1,15 +1,16 @@ --- title: Router --- + The router saves all paths used in the site. ## Get a Path The `get` method returns a [Stream]. For example, to save the path data to a specified destination: -``` js -var data = hexo.route.get('index.html'); -var dest = fs.createWriteStream('somewhere'); +```js +var data = hexo.route.get("index.html"); +var dest = fs.createWriteStream("somewhere"); data.pipe(dest); ``` @@ -18,32 +19,32 @@ data.pipe(dest); The `set` method takes a string, a [Buffer] or a function. -``` js +```js // String -hexo.route.set('index.html', 'index') +hexo.route.set("index.html", "index"); // Buffer -hexo.route.set('index.html', new Buffer('index')); +hexo.route.set("index.html", new Buffer("index")); // Function (Promise) -hexo.route.set('index.html', function(){ - return new Promise(function(resolve, reject){ - resolve('index'); +hexo.route.set("index.html", function () { + return new Promise(function (resolve, reject) { + resolve("index"); }); }); // Function (Callback) -hexo.route.set('index.html', function(callback){ - callback(null, 'index'); +hexo.route.set("index.html", function (callback) { + callback(null, "index"); }); ``` You can also set a boolean for whether a path has been modified or not. This can speed up file generation as it allows for ignoring the unmodified files. -``` js -hexo.route.set('index.html', { - data: 'index', - modified: false +```js +hexo.route.set("index.html", { + data: "index", + modified: false, }); // hexo.route.isModified('index.html') => false @@ -51,13 +52,13 @@ hexo.route.set('index.html', { ## Remove a Path -``` js -hexo.route.remove('index.html'); +```js +hexo.route.remove("index.html"); ``` ## Get the List of Routes -``` js +```js hexo.route.list(); ``` @@ -65,8 +66,8 @@ hexo.route.list(); The `format` method transforms a string to a valid path. -``` js -hexo.route.format('archives/'); +```js +hexo.route.format("archives/"); // archives/index.html ``` diff --git a/source/api/scaffolds.md b/source/api/scaffolds.md index 11f991ef69..e7ba7c37c1 100644 --- a/source/api/scaffolds.md +++ b/source/api/scaffolds.md @@ -1,20 +1,21 @@ --- title: Scaffolds --- + ## Get a Scaffold -``` js +```js hexo.scaffold.get(name); ``` ## Set a Scaffold -``` js +```js hexo.scaffold.set(name, content); ``` ## Remove a Scaffold -``` js +```js hexo.scaffold.remove(name); ``` diff --git a/source/api/tag.md b/source/api/tag.md index 1d061e1f11..eea7fe782f 100644 --- a/source/api/tag.md +++ b/source/api/tag.md @@ -1,14 +1,19 @@ --- title: Tag --- + A tag allows users to quickly and easily insert snippets into their posts. ## Synopsis -``` js -hexo.extend.tag.register(name, function(args, content){ - // ... -}, options); +```js +hexo.extend.tag.register( + name, + function (args, content) { + // ... + }, + options, +); ``` Two arguments will be passed into the tag function: `args` and `content`. `args` contains the arguments passed into the tag plugin and `content` is the wrapped content from the tag plugin. @@ -19,22 +24,22 @@ Since the introduction of asynchronous rendering in Hexo 3, we are using [Nunjuc Use `unregister()` to replace existing [tag plugins](/docs/tag-plugins) with custom functions. -``` js +```js hexo.extend.tag.unregister(name); ``` **Example** -``` js +```js const tagFn = (args, content) => { - content = 'something'; + content = "something"; return content; }; // https://hexo.io/docs/tag-plugins#YouTube -hexo.extend.tag.unregister('youtube'); +hexo.extend.tag.unregister("youtube"); -hexo.extend.tag.register('youtube', tagFn); +hexo.extend.tag.register("youtube", tagFn); ``` ## Options @@ -53,10 +58,14 @@ Enable async mode. This option is `false` by default. Insert a Youtube video. -``` js -hexo.extend.tag.register('youtube', function(args){ +```js +hexo.extend.tag.register("youtube", function (args) { var id = args[0]; - return '<div class="video-container"><iframe width="560" height="315" src="http://www.youtube.com/embed/' + id + '" frameborder="0" allowfullscreen></iframe></div>'; + return ( + '<div class="video-container"><iframe width="560" height="315" src="http://www.youtube.com/embed/' + + id + + '" frameborder="0" allowfullscreen></iframe></div>' + ); }); ``` @@ -64,29 +73,43 @@ hexo.extend.tag.register('youtube', function(args){ Insert a pull quote. -``` js -hexo.extend.tag.register('pullquote', function(args, content){ - var className = args.join(' '); - return '<blockquote class="pullquote' + className + '">' + content + '</blockquote>'; -}, {ends: true}); +```js +hexo.extend.tag.register( + "pullquote", + function (args, content) { + var className = args.join(" "); + return ( + '<blockquote class="pullquote' + + className + + '">' + + content + + "</blockquote>" + ); + }, + { ends: true }, +); ``` ### Async Rendering Insert a file. -``` js -var fs = require('hexo-fs'); -var pathFn = require('path'); - -hexo.extend.tag.register('include_code', function(args){ - var filename = args[0]; - var path = pathFn.join(hexo.source_dir, filename); - - return fs.readFile(path).then(function(content){ - return '<pre><code>' + content + '</code></pre>'; - }); -}, {async: true}); +```js +var fs = require("hexo-fs"); +var pathFn = require("path"); + +hexo.extend.tag.register( + "include_code", + function (args) { + var filename = args[0]; + var path = pathFn.join(hexo.source_dir, filename); + + return fs.readFile(path).then(function (content) { + return "<pre><code>" + content + "</code></pre>"; + }); + }, + { async: true }, +); ``` ## Front-matter and user configuration @@ -95,7 +118,7 @@ Any of the following options is valid: 1. -``` js +```js hexo.extend.tag.register('foo', function (args) { const [firstArg] = args; @@ -120,11 +143,11 @@ hexo.extend.tag.register('foo', function (args) { 2. -``` js index.js -hexo.extend.tag.register('foo', require('./lib/foo')(hexo)); +```js index.js +hexo.extend.tag.register("foo", require("./lib/foo")(hexo)); ``` -``` js lib/foo.js +```js lib/foo.js module.exports = hexo => { return function fooFn(args) { const [firstArg] = args; diff --git a/source/api/themes.md b/source/api/themes.md index 80814db565..8e4e6e54b6 100644 --- a/source/api/themes.md +++ b/source/api/themes.md @@ -1,23 +1,24 @@ --- title: Themes --- + `hexo.theme` inherits from [Box](box.html), and also saves templates. ## Get a View -``` js +```js hexo.theme.getView(path); ``` ## Set a View -``` js +```js hexo.theme.setView(path, data); ``` ## Remove a View -``` js +```js hexo.theme.removeView(path); ``` @@ -25,10 +26,10 @@ hexo.theme.removeView(path); Views have two methods: `render` and `renderSync`. These two methods are identical, but the former is asynchronous and the latter is synchronous. So for the sake of simplicity, we will only discuss `render` here. -``` js -var view = hexo.theme.getView('layout.swig'); +```js +var view = hexo.theme.getView("layout.swig"); -view.render({foo: 1, bar: 2}).then(function(result){ +view.render({ foo: 1, bar: 2 }).then(function (result) { // ... }); ``` diff --git a/source/docs/asset-folders.md b/source/docs/asset-folders.md index a8344f76a4..e99495b33c 100644 --- a/source/docs/asset-folders.md +++ b/source/docs/asset-folders.md @@ -1,6 +1,7 @@ --- title: Asset Folders --- + ## Global Asset Folder Assets are non-post files in the `source` folder, such as images, CSS or JavaScript files. For instance, If you are only going to have a few images in the Hexo project, then the easiest way is to keep them in a `source/images` directory. Then, you can access them using something like `![](/images/image.jpg)`. @@ -11,7 +12,7 @@ Assets are non-post files in the `source` folder, such as images, CSS or JavaScr For users who expect to regularly serve images and/or other assets, and for those who prefer to separate their assets on a post-per-post basis, Hexo also provides a more organized way to manage assets. This slightly more involved, but very convenient approach to asset management can be turned on by setting the `post_asset_folder` setting in `_config.yml` to true. -``` yaml _config.yml +```yaml _config.yml post_asset_folder: true ``` @@ -27,7 +28,7 @@ Referencing images or other assets using normal markdown syntax and relative pat {% asset_link slug [title] %} ``` -For example, with post asset folders enabled, if you place an image `example.jpg` into your asset folder, it will *not* appear on the index page if you reference it using a relative path with regular `![](example.jpg)` markdown syntax (however, it will work as expected in the post itself). +For example, with post asset folders enabled, if you place an image `example.jpg` into your asset folder, it will _not_ appear on the index page if you reference it using a relative path with regular `![](example.jpg)` markdown syntax (however, it will work as expected in the post itself). The correct way to reference the image will thus be using tag plugin syntax rather than markdown: @@ -44,7 +45,7 @@ This way, the image will appear both inside the post and on index and archive pa To enable: -``` yml _config.yml +```yml _config.yml post_asset_folder: true marked: prependRoot: true diff --git a/source/docs/commands.md b/source/docs/commands.md index 1f40cb8349..2734d86b5f 100644 --- a/source/docs/commands.md +++ b/source/docs/commands.md @@ -4,7 +4,7 @@ title: Commands ## init -``` bash +```bash $ hexo init [folder] ``` @@ -17,17 +17,17 @@ This command is a shortcut that runs the following steps: ## new -``` bash +```bash $ hexo new [layout] <title> ``` -Creates a new article. If no `layout` is provided, Hexo will use the `default_layout` from [_config.yml](configuration.html). Use the layout `draft` to create a draft. If the `title` contains spaces, surround it with quotation marks. +Creates a new article. If no `layout` is provided, Hexo will use the `default_layout` from [\_config.yml](configuration.html). Use the layout `draft` to create a draft. If the `title` contains spaces, surround it with quotation marks. -Option | Description ---- | --- -`-p`, `--path` | Post path. Customize the path of the post. -`-r`, `--replace` | Replace the current post if existed. -`-s`, `--slug` | Post slug. Customize the URL of the post. +| Option | Description | +| ----------------- | ------------------------------------------ | +| `-p`, `--path` | Post path. Customize the path of the post. | +| `-r`, `--replace` | Replace the current post if existed. | +| `-s`, `--slug` | Post slug. Customize the URL of the post. | By default, Hexo will use the title to define the path of the file. For pages, it will create a directory of that name and an `index.md` file in it. Use the `--path` option to override that behaviour and define the file path: @@ -47,23 +47,23 @@ will create the post `source/_posts/about/me.md` with the title "page" in the fr ## generate -``` bash +```bash $ hexo generate ``` Generates static files. -Option | Description ---- | --- -`-d`, `--deploy` | Deploy after generation finishes -`-w`, `--watch` | Watch file changes -`-b`, `--bail` | Raise an error if any unhandled exception is thrown during generation -`-f`, `--force` | Force regenerate -`-c`, `--concurrency` | Maximum number of files to be generated in parallel. Default is infinity +| Option | Description | +| --------------------- | ------------------------------------------------------------------------ | +| `-d`, `--deploy` | Deploy after generation finishes | +| `-w`, `--watch` | Watch file changes | +| `-b`, `--bail` | Raise an error if any unhandled exception is thrown during generation | +| `-f`, `--force` | Force regenerate | +| `-c`, `--concurrency` | Maximum number of files to be generated in parallel. Default is infinity | ## publish -``` bash +```bash $ hexo publish [layout] <filename> ``` @@ -71,45 +71,45 @@ Publishes a draft. ## server -``` bash +```bash $ hexo server ``` Starts a local server. By default, this is at `http://localhost:4000/`. -Option | Description ---- | --- -`-p`, `--port` | Override default port -`-s`, `--static` | Only serve static files -`-l`, `--log` | Enable logger. Override logger format. +| Option | Description | +| ---------------- | -------------------------------------- | +| `-p`, `--port` | Override default port | +| `-s`, `--static` | Only serve static files | +| `-l`, `--log` | Enable logger. Override logger format. | ## deploy -``` bash +```bash $ hexo deploy ``` Deploys your website. -Option | Description ---- | --- -`-g`, `--generate` | Generate before deployment +| Option | Description | +| ------------------ | -------------------------- | +| `-g`, `--generate` | Generate before deployment | ## render -``` bash +```bash $ hexo render <file1> [file2] ... ``` Renders files. -Option | Description ---- | --- -`-o`, `--output` | Output destination +| Option | Description | +| ---------------- | ------------------ | +| `-o`, `--output` | Output destination | ## migrate -``` bash +```bash $ hexo migrate <type> ``` @@ -117,7 +117,7 @@ $ hexo migrate <type> ## clean -``` bash +```bash $ hexo clean ``` @@ -125,7 +125,7 @@ Cleans the cache file (`db.json`) and generated files (`public`). ## list -``` bash +```bash $ hexo list <type> ``` @@ -133,7 +133,7 @@ Lists all routes. ## version -``` bash +```bash $ hexo version ``` @@ -151,7 +151,7 @@ Lists the configuration (`_config.yml`). If `key` is specified, only the value o ### Safe mode -``` bash +```bash $ hexo --safe ``` @@ -159,7 +159,7 @@ Disables loading plugins and scripts. Try this if you encounter problems after i ### Debug mode -``` bash +```bash $ hexo --debug ``` @@ -167,7 +167,7 @@ Logs verbose messages to the terminal and to `debug.log`. Try this if you encoun ### Silent mode -``` bash +```bash $ hexo --silent ``` @@ -175,19 +175,19 @@ Silences output to the terminal. ### Customize config file path -``` bash +```bash $ hexo --config custom.yml ``` Uses a custom config file (instead of `_config.yml`). Also accepts a comma-separated list (no spaces) of JSON or YAML config files that will combine the files into a single `_multiconfig.yml`. -``` bash +```bash $ hexo --config custom.yml,custom2.json ``` ### Display drafts -``` bash +```bash $ hexo --draft ``` @@ -195,7 +195,7 @@ Displays draft posts (stored in the `source/_drafts` folder). ### Customize CWD -``` bash +```bash $ hexo --cwd /path/to/cwd ``` diff --git a/source/docs/configuration.md b/source/docs/configuration.md index 50b1d71922..bddaa540fa 100644 --- a/source/docs/configuration.md +++ b/source/docs/configuration.md @@ -1,31 +1,32 @@ --- title: Configuration --- + You can modify site settings in `_config.yml` or in an [alternate config file](#Using-an-Alternate-Config). ### Site -Setting | Description ---- | --- -`title` | The title of your website -`subtitle` | The subtitle of your website -`description` | The description of your website -`keywords` | The keywords of your website. Supports multiple values. -`author` | Your name -`language` | The language of your website. Use a [2-letter ISO-639-1 code](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) or optionally [its variant](/docs/internationalization). Default is `en`. -`timezone` | The timezone of your website. Hexo uses the setting on your computer by default. You can find the list of available timezones [here](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). Some examples are `America/New_York`, `Japan`, and `UTC`. +| Setting | Description | +| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `title` | The title of your website | +| `subtitle` | The subtitle of your website | +| `description` | The description of your website | +| `keywords` | The keywords of your website. Supports multiple values. | +| `author` | Your name | +| `language` | The language of your website. Use a [2-letter ISO-639-1 code](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) or optionally [its variant](/docs/internationalization). Default is `en`. | +| `timezone` | The timezone of your website. Hexo uses the setting on your computer by default. You can find the list of available timezones [here](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). Some examples are `America/New_York`, `Japan`, and `UTC`. | ### URL -Setting | Description | Default ---- | --- | --- -`url` | The URL of your website, must start with `http://` or `https://` | -`root` | The root directory of your website | `url's pathname` -`permalink` | The [permalink](permalinks.html) format of articles | `:year/:month/:day/:title/` -`permalink_defaults` | Default values of each segment in permalink | -`pretty_urls` | Rewrite the [`permalink`](permalinks.html) variables to pretty URLs | -`pretty_urls.trailing_index` | Trailing `index.html`, set to `false` to remove it | `true` -`pretty_urls.trailing_html` | Trailing `.html`, set to `false` to remove it (_does not apply to trailing `index.html`_) | `true` +| Setting | Description | Default | +| ---------------------------- | ----------------------------------------------------------------------------------------- | --------------------------- | +| `url` | The URL of your website, must start with `http://` or `https://` | +| `root` | The root directory of your website | `url's pathname` | +| `permalink` | The [permalink](permalinks.html) format of articles | `:year/:month/:day/:title/` | +| `permalink_defaults` | Default values of each segment in permalink | +| `pretty_urls` | Rewrite the [`permalink`](permalinks.html) variables to pretty URLs | +| `pretty_urls.trailing_index` | Trailing `index.html`, set to `false` to remove it | `true` | +| `pretty_urls.trailing_html` | Trailing `.html`, set to `false` to remove it (_does not apply to trailing `index.html`_) | `true` | {% note info Website in subdirectory %} If your website is in a subdirectory (such as `http://example.org/blog`) set `url` to `http://example.org/blog` and set `root` to `/blog/`. @@ -33,7 +34,7 @@ If your website is in a subdirectory (such as `http://example.org/blog`) set `ur Examples: -``` yaml +```yaml # e.g. page.permalink is http://example.com/foo/bar/index.html pretty_urls: trailing_index: false @@ -42,20 +43,20 @@ pretty_urls: ### Directory -Setting | Description | Default ---- | --- | --- -`source_dir` | Source folder. Where your content is stored | `source` -`public_dir` | Public folder. Where the static site will be generated | `public` -`tag_dir` | Tag directory | `tags` -`archive_dir` | Archive directory | `archives` -`category_dir` | Category directory | `categories` -`code_dir` | Include code directory (subdirectory of `source_dir`) | `downloads/code` -`i18n_dir` | i18n directory | `:lang` -`skip_render` | Paths that will be copied to `public` raw, without being rendered. You can use [glob expressions](https://github.com/micromatch/micromatch#extended-globbing) for path matching. +| Setting | Description | Default | +| -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------- | +| `source_dir` | Source folder. Where your content is stored | `source` | +| `public_dir` | Public folder. Where the static site will be generated | `public` | +| `tag_dir` | Tag directory | `tags` | +| `archive_dir` | Archive directory | `archives` | +| `category_dir` | Category directory | `categories` | +| `code_dir` | Include code directory (subdirectory of `source_dir`) | `downloads/code` | +| `i18n_dir` | i18n directory | `:lang` | +| `skip_render` | Paths that will be copied to `public` raw, without being rendered. You can use [glob expressions](https://github.com/micromatch/micromatch#extended-globbing) for path matching. | Examples: -``` yaml +```yaml skip_render: "mypage/**/*" # will output `source/mypage/index.html` and `source/mypage/code.js` without altering them. @@ -66,45 +67,45 @@ skip_render: "_posts/test-post.md" ### Writing -Setting | Description | Default ---- | --- | --- -`new_post_name` | The filename format for new posts | `:title.md` -`default_layout` | Default layout | `post` -`titlecase` | Transform titles into title case? | `false` -`external_link` | Open external links in a new tab? | -`external_link.enable` | Open external links in a new tab? | `true` -`external_link.field` | Applies to the whole `site` or `post` only | `site` -`external_link.exclude` | Exclude hostname. Specify subdomain when applicable, including `www` | `[]` -`filename_case` | Transform filenames to `1` lower case; `2` upper case | `0` -`render_drafts` | Display drafts? | `false` -`post_asset_folder` | Enable the [Asset Folder](asset-folders.html)? | `false` -`relative_link` | Make links relative to the root folder? | `false` -`future` | Display future posts? | `true` -`syntax_highlighter` | Code block syntax highlight settings, see [Syntax Highlight](/docs/syntax-highlight) section for usage guide | `highlight.js` -`highlight` | Code block syntax highlight settings, see [Highlight.js](/docs/syntax-highlight#Highlight-js) section for usage guide | -`prismjs` | Code block syntax highlight settings, see [PrismJS](/docs/syntax-highlight#PrismJS) section for usage guide | +| Setting | Description | Default | +| ----------------------- | --------------------------------------------------------------------------------------------------------------------- | -------------- | +| `new_post_name` | The filename format for new posts | `:title.md` | +| `default_layout` | Default layout | `post` | +| `titlecase` | Transform titles into title case? | `false` | +| `external_link` | Open external links in a new tab? | +| `external_link.enable` | Open external links in a new tab? | `true` | +| `external_link.field` | Applies to the whole `site` or `post` only | `site` | +| `external_link.exclude` | Exclude hostname. Specify subdomain when applicable, including `www` | `[]` | +| `filename_case` | Transform filenames to `1` lower case; `2` upper case | `0` | +| `render_drafts` | Display drafts? | `false` | +| `post_asset_folder` | Enable the [Asset Folder](asset-folders.html)? | `false` | +| `relative_link` | Make links relative to the root folder? | `false` | +| `future` | Display future posts? | `true` | +| `syntax_highlighter` | Code block syntax highlight settings, see [Syntax Highlight](/docs/syntax-highlight) section for usage guide | `highlight.js` | +| `highlight` | Code block syntax highlight settings, see [Highlight.js](/docs/syntax-highlight#Highlight-js) section for usage guide | +| `prismjs` | Code block syntax highlight settings, see [PrismJS](/docs/syntax-highlight#PrismJS) section for usage guide | ### Home page setting -Setting | Description | Default ---- | --- | --- -`index_generator` | Generate an archive of posts, powered by [hexo-generator-index](https://github.com/hexojs/hexo-generator-index) | -`index_generator.path` | Root path for your blog's index page | `''` -`index_generator.per_page` | Posts displayed per page. | `10` -`index_generator.order_by` | Posts order. Order by descending date (new to old) by default. | `-date` -`index_generator.pagination_dir` | URL format, see [Pagination](#Pagination) setting below | `page` +| Setting | Description | Default | +| -------------------------------- | --------------------------------------------------------------------------------------------------------------- | ------- | +| `index_generator` | Generate an archive of posts, powered by [hexo-generator-index](https://github.com/hexojs/hexo-generator-index) | +| `index_generator.path` | Root path for your blog's index page | `''` | +| `index_generator.per_page` | Posts displayed per page. | `10` | +| `index_generator.order_by` | Posts order. Order by descending date (new to old) by default. | `-date` | +| `index_generator.pagination_dir` | URL format, see [Pagination](#Pagination) setting below | `page` | ### Category & Tag -Setting | Description | Default ---- | --- | --- -`default_category` | Default category | `uncategorized` -`category_map` | Override category slugs | -`tag_map` | Override tag slugs | +| Setting | Description | Default | +| ------------------ | ----------------------- | --------------- | +| `default_category` | Default category | `uncategorized` | +| `category_map` | Override category slugs | +| `tag_map` | Override tag slugs | Examples: -``` yaml +```yaml category_map: "yesterday's thoughts": yesterdays-thoughts "C++": c-plus-plus @@ -114,11 +115,11 @@ category_map: Hexo uses [Moment.js](http://momentjs.com/) to process dates. -Setting | Description | Default ---- | --- | --- -`date_format` | Date format | `YYYY-MM-DD` -`time_format` | Time format | `HH:mm:ss` -`updated_option` | The [`updated`](/docs/variables#Page-Variables) value to used when not provided in the front-matter | `mtime` +| Setting | Description | Default | +| ---------------- | --------------------------------------------------------------------------------------------------- | ------------ | +| `date_format` | Date format | `YYYY-MM-DD` | +| `time_format` | Time format | `HH:mm:ss` | +| `updated_option` | The [`updated`](/docs/variables#Page-Variables) value to used when not provided in the front-matter | `mtime` | {% note info updated_option %} `updated_option` controls the `updated` value when not provided in the front-matter: @@ -132,14 +133,14 @@ Setting | Description | Default ### Pagination -Setting | Description | Default ---- | --- | --- -`per_page` | Number of posts displayed on each page. `0` disables pagination | `10` -`pagination_dir` | URL format | `page` +| Setting | Description | Default | +| ---------------- | --------------------------------------------------------------- | ------- | +| `per_page` | Number of posts displayed on each page. `0` disables pagination | `10` | +| `pagination_dir` | URL format | `page` | Examples: -``` yaml +```yaml pagination_dir: 'page' # http://example.com/page/2 @@ -149,12 +150,12 @@ pagination_dir: 'awesome-page' ### Extensions -Setting | Description ---- | --- -`theme` | Theme name. `false` disables theming -`theme_config` | Theme configuration. Include any custom theme settings under this key to override theme defaults. -`deploy` | Deployment settings -`meta_generator` | [Meta generator](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta#Attributes) tag. `false` disables injection of the tag. +| Setting | Description | +| ---------------- | --------------------------------------------------------------------------------------------------------------------------------------- | +| `theme` | Theme name. `false` disables theming | +| `theme_config` | Theme configuration. Include any custom theme settings under this key to override theme defaults. | +| `deploy` | Deployment settings | +| `meta_generator` | [Meta generator](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta#Attributes) tag. `false` disables injection of the tag. | ### Include/Exclude Files or Folders @@ -162,11 +163,11 @@ Use the following options to explicitly process or ignore certain files/folders. `include` and `exclude` options only apply to the `source/` folder, whereas `ignore` option applies to all folders. -Setting | Description ---- | --- -`include` | Include hidden files (including files/folders with a name that starts with an underscore, with an exception*) -`exclude` | Exclude files/folders -`ignore` | Ignore files/folders +| Setting | Description | +| --------- | -------------------------------------------------------------------------------------------------------------- | +| `include` | Include hidden files (including files/folders with a name that starts with an underscore, with an exception\*) | +| `exclude` | Exclude files/folders | +| `ignore` | Ignore files/folders | Examples: @@ -215,7 +216,7 @@ Each value in the list must be enclosed with single/double quotes. A custom config file path can be specified by adding the `--config` flag to your `hexo` commands with a path to an alternate YAML or JSON config file, or a comma-separated list (no spaces) of multiple YAML or JSON files. -``` bash +```bash # use 'custom.yml' in place of '_config.yml' $ hexo server --config custom.yml @@ -243,7 +244,7 @@ theme: "my-theme" theme_config: bio: "My awesome bio" foo: - bar: 'a' + bar: "a" ``` ```yml @@ -258,11 +259,11 @@ Resulting in theme configuration: ```json { - bio: "My awesome bio", - logo: "a-cool-image.png", - foo: { - bar: "a", - baz: "b" + "bio": "My awesome bio", + "logo": "a-cool-image.png", + "foo": { + "bar": "a", + "baz": "b" } } ``` @@ -282,7 +283,7 @@ theme: "my-theme" # _config.my-theme.yml bio: "My awesome bio" foo: - bar: 'a' + bar: "a" ``` ```yml @@ -297,11 +298,11 @@ Resulting in theme configuration: ```json { - bio: "My awesome bio", - logo: "a-cool-image.png", - foo: { - bar: "a", - baz: "b" + "bio": "My awesome bio", + "logo": "a-cool-image.png", + "foo": { + "bar": "a", + "baz": "b" } } ``` diff --git a/source/docs/contributing.md b/source/docs/contributing.md index db8141a02b..2ad1f1bc7b 100644 --- a/source/docs/contributing.md +++ b/source/docs/contributing.md @@ -25,7 +25,7 @@ Also, Hexo has its own [ESLint config](https://github.com/hexojs/eslint-config-h 1. Fork [hexojs/hexo]. 2. Clone the repository to your computer and install dependencies. -``` bash +```bash $ git clone https://github.com/<username>/hexo.git $ cd hexo $ npm install @@ -34,7 +34,7 @@ $ git submodule update --init 3. Create a feature branch. -``` bash +```bash $ git checkout -b new_feature ``` @@ -52,7 +52,7 @@ $ git push origin new_feature - Please don't modify version number in `package.json`. - Your pull request will only get merged when tests passed. Don't forget to run tests before submission. -``` bash +```bash $ npm test ``` @@ -69,7 +69,7 @@ The Hexo documentation is open source and you can find the source code on [hexoj 1. Fork [hexojs/site] 2. Clone the repository to your computer and install dependencies. -``` bash +```bash $ npm install hexo-cli -g # If you don't have hexo-cli installed $ git clone https://github.com/<username>/site.git $ cd site @@ -78,7 +78,7 @@ $ npm install 3. Start editing the documentation. You can start the server for live previewing. -``` bash +```bash $ hexo server ``` diff --git a/source/docs/data-files.md b/source/docs/data-files.md index 98931f7da9..e9474aab1a 100644 --- a/source/docs/data-files.md +++ b/source/docs/data-files.md @@ -1,13 +1,14 @@ --- title: Data Files --- + Sometimes you may need to use some data in templates which is not directly available in your posts, or you want to reuse the data elsewhere. For such use cases, Hexo 3 introduced the new **Data files**. This feature loads YAML or JSON files in `source/_data` folder so you can use them in your site. {% youtube CN31plHbI-w %} For example, add `menu.yml` in `source/_data` folder. -``` yaml +```yaml Home: / Gallery: /gallery/ Archives: /archives/ diff --git a/source/docs/front-matter.md b/source/docs/front-matter.md index 6513643b22..6eade09ebd 100644 --- a/source/docs/front-matter.md +++ b/source/docs/front-matter.md @@ -8,7 +8,7 @@ Front-matter is a block of YAML or JSON at the beginning of the file that is use **YAML** -``` yaml +```yaml --- title: Hello World date: 2013/7/13 20:46:25 @@ -17,7 +17,7 @@ date: 2013/7/13 20:46:25 **JSON** -``` json +```json "title": "Hello World", "date": "2013/7/13 20:46:25" ;;; @@ -25,20 +25,20 @@ date: 2013/7/13 20:46:25 ### Settings & Their Default Values -Setting | Description | Default ---- | --- | --- -`layout` | Layout | [`config.default_layout`](/docs/configuration#Writing) -`title` | Title | Filename (posts only) -`date` | Published date | File created date -`updated` | Updated date | File updated date -`comments` | Enables comment feature for the post | `true` -`tags` | Tags (Not available for pages) | -`categories` | Categories (Not available for pages) | -`permalink` | Overrides the default permalink of the post. Permalink should end with `/` or `.html` | `null` -`excerpt` | Page excerpt in plain text. Use [this plugin](/docs/tag-plugins#Post-Excerpt) to format the text | -`disableNunjucks` | Disable rendering of Nunjucks tag `{{ }}`/`{% %}` and [tag plugins](/docs/tag-plugins) when enabled | false -`lang` | Set the language to override [auto-detection](/docs/internationalization#Path) | Inherited from `_config.yml` -`published` | Whether the post should be published | For posts under `_posts`, it is `true`, and for posts under `_draft`, it is `false` +| Setting | Description | Default | +| ----------------- | --------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | +| `layout` | Layout | [`config.default_layout`](/docs/configuration#Writing) | +| `title` | Title | Filename (posts only) | +| `date` | Published date | File created date | +| `updated` | Updated date | File updated date | +| `comments` | Enables comment feature for the post | `true` | +| `tags` | Tags (Not available for pages) | +| `categories` | Categories (Not available for pages) | +| `permalink` | Overrides the default permalink of the post. Permalink should end with `/` or `.html` | `null` | +| `excerpt` | Page excerpt in plain text. Use [this plugin](/docs/tag-plugins#Post-Excerpt) to format the text | +| `disableNunjucks` | Disable rendering of Nunjucks tag `{{ }}`/`{% %}` and [tag plugins](/docs/tag-plugins) when enabled | false | +| `lang` | Set the language to override [auto-detection](/docs/internationalization#Path) | Inherited from `_config.yml` | +| `published` | Whether the post should be published | For posts under `_posts`, it is `true`, and for posts under `_draft`, it is `false` | #### Layout @@ -52,24 +52,24 @@ Only posts support the use of categories and tags. Categories apply to posts in **Example** -``` yaml +```yaml categories: -- Sports -- Baseball + - Sports + - Baseball tags: -- Injury -- Fight -- Shocking + - Injury + - Fight + - Shocking ``` If you want to apply multiple category hierarchies, use a list of names instead of a single name. If Hexo sees any categories defined this way on a post, it will treat each category for that post as its own independent hierarchy. **Example** -``` yaml +```yaml categories: -- [Sports, Baseball] -- [MLB, American League, Boston Red Sox] -- [MLB, American League, New York Yankees] -- Rivalries + - [Sports, Baseball] + - [MLB, American League, Boston Red Sox] + - [MLB, American League, New York Yankees] + - Rivalries ``` diff --git a/source/docs/generating.md b/source/docs/generating.md index 6646ee0dea..2cd48f4208 100644 --- a/source/docs/generating.md +++ b/source/docs/generating.md @@ -1,9 +1,10 @@ --- title: Generating --- + Generating static files with Hexo is quite easy and fast. -``` bash +```bash $ hexo generate ``` @@ -13,7 +14,7 @@ $ hexo generate Hexo can watch for file changes and regenerate files immediately. Hexo will compare the SHA1 checksum of your files and only write if file changes are detected. -``` bash +```bash $ hexo generate --watch ``` @@ -21,7 +22,7 @@ $ hexo generate --watch To deploy after generating, you can run one of the following commands. There is no difference between the two. -``` bash +```bash $ hexo generate --deploy $ hexo deploy --generate ``` diff --git a/source/docs/github-pages.md b/source/docs/github-pages.md index 5b14b07764..01491e3cef 100644 --- a/source/docs/github-pages.md +++ b/source/docs/github-pages.md @@ -4,14 +4,16 @@ title: GitHub Pages In this tutorial, we use [GitHub Actions](https://docs.github.com/en/actions) to deploy GitHub Pages. It works in both public and private repositories. Skip to the [One-command deployment](#One-command-deployment) section if you prefer not to upload your source folder to GitHub. -1. Create a repo named <b>*username*.github.io</b>, where username is your username on GitHub. If you have already uploaded to another repo, rename the repo instead. +1. Create a repo named <b>_username_.github.io</b>, where username is your username on GitHub. If you have already uploaded to another repo, rename the repo instead. 2. Push the files of your Hexo folder to the default branch of your repository. The default branch is usually **main**, older repositories may use **master** branch. - - To push `main` branch to GitHub: - ``` - $ git push -u origin main - ``` - - The `public/` folder is not (and should not be) uploaded by default, make sure the `.gitignore` file contains `public/` line. The folder structure should be roughly similar to [this repo](https://github.com/hexojs/hexo-starter). +- To push `main` branch to GitHub: + + ``` + $ git push -u origin main + ``` + +- The `public/` folder is not (and should not be) uploaded by default, make sure the `.gitignore` file contains `public/` line. The folder structure should be roughly similar to [this repo](https://github.com/hexojs/hexo-starter). 3. Check what version of Node.js you are using on your local machine with `node --version`. Make a note of the major version (e.g., `v20.y.z`) 4. In your GitHub repo's setting, navigate to **Settings** > **Pages** > **Source**. Change the source to **GitHub Actions** and save. @@ -23,7 +25,7 @@ name: Pages on: push: branches: - - main # default branch + - main # default branch jobs: build: @@ -39,7 +41,7 @@ jobs: with: # Examples: 20, 18.19, >=16.20.2, lts/Iron, lts/Hydrogen, *, latest, current, node # Ref: https://github.com/actions/setup-node#supported-version-syntax - node-version: '20' + node-version: "20" - name: Cache NPM dependencies uses: actions/cache@v4 with: @@ -70,7 +72,7 @@ jobs: uses: actions/deploy-pages@v4 ``` -6. Once the deployment is finished, check the webpage at *username*.github.io. +6. Once the deployment is finished, check the webpage at _username_.github.io. Note - if you specify a custom domain name with a `CNAME`, you need to add the `CNAME` file to the `source/` folder. [More info](https://docs.github.com/en/pages/configuring-a-custom-domain-for-your-github-pages-site/managing-a-custom-domain-for-your-github-pages-site). @@ -78,29 +80,29 @@ Note - if you specify a custom domain name with a `CNAME`, you need to add the ` If you prefer to have a project page on GitHub: -1. Navigate to your repo on GitHub. Go to the **Settings** tab. Change the **Repository name** so your blog is available at <b>username.github.io/*repository*</b>, **repository** can be any name, like *blog* or *hexo*. -2. Edit your **_config.yml**, change the `url:` value to <b>https://*username*.github.io/*repository*</b>. +1. Navigate to your repo on GitHub. Go to the **Settings** tab. Change the **Repository name** so your blog is available at <b>username.github.io/_repository_</b>, **repository** can be any name, like _blog_ or _hexo_. +2. Edit your **\_config.yml**, change the `url:` value to <b>https://_username_.github.io/_repository_</b>. 3. In your GitHub repo's setting, navigate to **Settings** > **Pages** > **Source**. Change the source to **GitHub Actions** and save. 4. Commit and push to the default branch. -4. Once the deployment is finished, check the webpage at *username*.github.io/*repository*. +5. Once the deployment is finished, check the webpage at _username_.github.io/_repository_. ## One-command deployment The following instruction is adapted from [one-command deployment](/docs/one-command-deployment) page. 1. Install [hexo-deployer-git](https://github.com/hexojs/hexo-deployer-git). -2. Add the following configurations to **_config.yml**, (remove existing lines if any). - - ``` yml - deploy: - type: git - repo: https://github.com/<username>/<project> - # example, https://github.com/hexojs/hexojs.github.io - branch: gh-pages - ``` +2. Add the following configurations to **\_config.yml**, (remove existing lines if any). + +```yml +deploy: + type: git + repo: https://github.com/<username>/<project> + # example, https://github.com/hexojs/hexojs.github.io + branch: gh-pages +``` 3. Run `hexo clean && hexo deploy`. -4. Check the webpage at *username*.github.io. +4. Check the webpage at _username_.github.io. ## Useful links diff --git a/source/docs/gitlab-pages.md b/source/docs/gitlab-pages.md index b79ffb27d6..ac0b2f64bc 100644 --- a/source/docs/gitlab-pages.md +++ b/source/docs/gitlab-pages.md @@ -2,13 +2,13 @@ title: GitLab Pages --- -1. Create a new repository named <b>*username*.gitlab.io</b>, where username is your username on GitLab. If you have already uploaded to other repo, rename the repo instead. +1. Create a new repository named <b>_username_.gitlab.io</b>, where username is your username on GitLab. If you have already uploaded to other repo, rename the repo instead. 2. Enable Shared Runners via **Settings** > **CI/CD** > **Runners** > **Enable shared runners for this project**. 3. Push the files of your Hexo folder to the repository. The `public/` folder is not (and should not be) uploaded by default, make sure the `.gitignore` file contains `public/` line. The folder structure should be roughly similar to [this repo](https://gitlab.com/pages/hexo). 4. Check what version of Node.js you are using on your local machine with `node --version`. Make a note of the major version (e.g., `v16.y.z`) -5. Add `.gitlab-ci.yml` file to the root folder of your repo (alongside _config.yml & package.json) with the following content (replacing `16` with the major version of Node.js you noted in previous step): +5. Add `.gitlab-ci.yml` file to the root folder of your repo (alongside \_config.yml & package.json) with the following content (replacing `16` with the major version of Node.js you noted in previous step): -``` yml +```yml image: node:16-alpine cache: paths: @@ -28,15 +28,15 @@ pages: - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH ``` -6. *username*.gitlab.io should be up and running, once GitLab CI finishes the deployment job, +6. _username_.gitlab.io should be up and running, once GitLab CI finishes the deployment job, 7. (Optional) If you wish to inspect the generated site assets (html, css, js, etc), they can be found in the [job artifact](https://docs.gitlab.com/ee/ci/pipelines/job_artifacts.html). ## Project page If you prefer to have a project page on GitLab: -1. Go to **Settings** > **General** > **Advanced** > **Change path**. Change the value to a name, so the website is available at <b>username.gitlab.io/*repository*</b>. It can be any name, like *blog* or *hexo*. -2. Edit **_config.yml**, change the `url:` value to `https://username.gitlab.io/repository`. +1. Go to **Settings** > **General** > **Advanced** > **Change path**. Change the value to a name, so the website is available at <b>username.gitlab.io/_repository_</b>. It can be any name, like _blog_ or _hexo_. +2. Edit **\_config.yml**, change the `url:` value to `https://username.gitlab.io/repository`. 3. Commit and push. ## Useful links diff --git a/source/docs/helpers.md b/source/docs/helpers.md index fb6044f9a2..9fec5e4ad6 100644 --- a/source/docs/helpers.md +++ b/source/docs/helpers.md @@ -1,7 +1,8 @@ --- title: Helpers --- -Helpers are used in templates to help you insert snippets quickly. Helpers cannot be used in source files. + +Helpers are used in templates to help you insert snippets quickly. Helpers cannot be used in source files. You could easily [write your own custom helper](https://hexo.io/api/helper.html) or use our ready-made helpers. @@ -13,22 +14,22 @@ You could easily [write your own custom helper](https://hexo.io/api/helper.html) Returns a URL with the root path prefixed. Output is encoded automatically. -``` js +```js <%- url_for(path, [option]) %> ``` -Option | Description | Default ---- | --- | --- -`relative` | Output relative link | Value of `config.relative_link` +| Option | Description | Default | +| ---------- | -------------------- | ------------------------------- | +| `relative` | Output relative link | Value of `config.relative_link` | **Examples:** -``` yml +```yml _config.yml root: /blog/ # example ``` -``` js +```js <%- url_for('/a/path') %> // /blog/a/path ``` @@ -36,12 +37,12 @@ root: /blog/ # example Relative link, follows `relative_link` option by default e.g. post/page path is '/foo/bar/index.html' -``` yml +```yml _config.yml relative_link: true ``` -``` js +```js <%- url_for('/css/style.css') %> // ../../css/style.css @@ -57,13 +58,13 @@ relative_link: true Returns the relative URL from `from` to `to`. -``` js +```js <%- relative_url(from, to) %> ``` **Examples:** -``` js +```js <%- relative_url('foo/bar/', 'css/style.css') %> // ../../css/style.css ``` @@ -72,18 +73,18 @@ Returns the relative URL from `from` to `to`. Returns a URL with the `config.url` prefixed. Output is encoded automatically. -``` js +```js <%- full_url_for(path) %> ``` **Examples:** -``` yml +```yml _config.yml url: https://example.com/blog # example ``` -``` js +```js <%- full_url_for('/a/path') %> // https://example.com/blog/a/path ``` @@ -94,22 +95,22 @@ Returns the gravatar image URL from an email. If you don't specify the [options] parameter, the default options will apply. Otherwise, you can set it to a number which will then be passed on as the size parameter to Gravatar. Finally, if you set it to an object, it will be converted into a query string of parameters for Gravatar. -``` js +```js <%- gravatar(email, [options]) %> ``` -Option | Description | Default ---- | --- | --- -`s` | Output image size | 80 -`d` | Default image | -`f` | Force default | -`r` | Rating | +| Option | Description | Default | +| ------ | ----------------- | ------- | +| `s` | Output image size | 80 | +| `d` | Default image | +| `f` | Force default | +| `r` | Rating | More info: [Gravatar](https://en.gravatar.com/site/implement/images/) **Examples:** -``` js +```js <%- gravatar('a@abc.com') %> // https://www.gravatar.com/avatar/b9b00e66c6b8a70f88c73cb6bdb06787 @@ -126,13 +127,13 @@ More info: [Gravatar](https://en.gravatar.com/site/implement/images/) Loads CSS files. `path` can be an array or a string. `path` can be a string, an array, an object or an array of objects. [`/<root>/`](/docs/configuration#URL) value is prepended while `.css` extension is appended to the `path` automatically. Use object type for custom attributes. -``` js +```js <%- css(path, ...) %> ``` **Examples:** -``` js +```js <%- css('style.css') %> // <link rel="stylesheet" href="/style.css"> @@ -152,13 +153,13 @@ Loads CSS files. `path` can be an array or a string. `path` can be a string, an Loads JavaScript files. `path` can be a string, an array, an object or an array of objects. [`/<root>/`](/docs/configuration#URL) value is prepended while `.js` extension is appended to the `path` automatically. Use object type for custom attributes. -``` js +```js <%- js(path, ...) %> ``` **Examples:** -``` js +```js <%- js('script.js') %> // <script src="/script.js"></script> @@ -178,19 +179,19 @@ Loads JavaScript files. `path` can be a string, an array, an object or an array Inserts a link. -``` js +```js <%- link_to(path, [text], [options]) %> ``` -Option | Description | Default ---- | --- | --- -`external` | Opens the link in a new tab | false -`class` | Class name | -`id` | ID | +| Option | Description | Default | +| ---------- | --------------------------- | ------- | +| `external` | Opens the link in a new tab | false | +| `class` | Class name | +| `id` | ID | **Examples:** -``` js +```js <%- link_to('http://www.google.com') %> // <a href="http://www.google.com" title="http://www.google.com">http://www.google.com</a> @@ -205,22 +206,22 @@ Option | Description | Default Inserts a mail link. -``` js +```js <%- mail_to(path, [text], [options]) %> ``` -Option | Description ---- | --- -`class` | Class name -`id` | ID -`subject` | Mail subject -`cc` | CC -`bcc` | BCC -`body` | Mail content +| Option | Description | +| --------- | ------------ | +| `class` | Class name | +| `id` | ID | +| `subject` | Mail subject | +| `cc` | CC | +| `bcc` | BCC | +| `body` | Mail content | **Examples:** -``` js +```js <%- mail_to('a@abc.com') %> // <a href="mailto:a@abc.com" title="a@abc.com">a@abc.com</a> @@ -232,23 +233,23 @@ Option | Description Inserts an image. -``` js +```js <%- image_tag(path, [options]) %> ``` -Option | Description ---- | --- -`alt` | Alternative text of the image -`class` | Class name -`id` | ID -`width` | Image width -`height` | Image height +| Option | Description | +| -------- | ----------------------------- | +| `alt` | Alternative text of the image | +| `class` | Class name | +| `id` | ID | +| `width` | Image width | +| `height` | Image height | ### favicon_tag Inserts a favicon. -``` js +```js <%- favicon_tag(path) %> ``` @@ -256,18 +257,18 @@ Inserts a favicon. Inserts a feed link. -``` js +```js <%- feed_tag(path, [options]) %> ``` -Option | Description | Default ---- | --- | --- -`title` | Feed title | `config.title` -`type` | Feed type | +| Option | Description | Default | +| ------- | ----------- | -------------- | +| `title` | Feed title | `config.title` | +| `type` | Feed type | **Examples:** -``` js +```js <%- feed_tag('atom.xml') %> // <link rel="alternate" href="/atom.xml" title="Hexo" type="application/atom+xml"> @@ -285,7 +286,7 @@ Option | Description | Default Check whether `path` matches the URL of the current page. Use `strict` options to enable strict matching. -``` js +```js <%- is_current(path, [strict]) %> ``` @@ -293,7 +294,7 @@ Check whether `path` matches the URL of the current page. Use `strict` options t Check whether the current page is home page. -``` js +```js <%- is_home() %> ``` @@ -301,7 +302,7 @@ Check whether the current page is home page. Check whether the current page is the first of home page. -``` js +```js <%- is_home_first_page() %> ``` @@ -309,7 +310,7 @@ Check whether the current page is the first of home page. Check whether the current page is a post. -``` js +```js <%- is_post() %> ``` @@ -317,7 +318,7 @@ Check whether the current page is a post. Check whether the current page is a page. -``` js +```js <%- is_page() %> ``` @@ -325,7 +326,7 @@ Check whether the current page is a page. Check whether the current page is an archive page. -``` js +```js <%- is_archive() %> ``` @@ -333,7 +334,7 @@ Check whether the current page is an archive page. Check whether the current page is a yearly archive page. -``` js +```js <%- is_year() %> ``` @@ -341,7 +342,7 @@ Check whether the current page is a yearly archive page. Check whether the current page is a monthly archive page. -``` js +```js <%- is_month() %> ``` @@ -350,7 +351,7 @@ Check whether the current page is a monthly archive page. Check whether the current page is a category page. If a string is given as parameter, check whether the current page match the given category. -``` js +```js <%- is_category() %> <%- is_category('hobby') %> ``` @@ -360,7 +361,7 @@ If a string is given as parameter, check whether the current page match the give Check whether the current page is a tag page. If a string is given as parameter, check whether the current page match the given tag. -``` js +```js <%- is_tag() %> <%- is_tag('hobby') %> ``` @@ -371,7 +372,7 @@ If a string is given as parameter, check whether the current page match the give Removes prefixing and trailing spaces of a string. -``` js +```js <%- trim(string) %> ``` @@ -379,13 +380,13 @@ Removes prefixing and trailing spaces of a string. Sanitizes all HTML tags in a string. -``` js +```js <%- strip_html(string) %> ``` **Examples:** -``` js +```js <%- strip_html('It\'s not <b>important</b> anymore!') %> // It's not important anymore! ``` @@ -394,13 +395,13 @@ Sanitizes all HTML tags in a string. Transforms a string into proper title caps. -``` js +```js <%- titlecase(string) %> ``` **Examples:** -``` js +```js <%- titlecase('this is an apple') %> # This is an Apple ``` @@ -409,13 +410,13 @@ Transforms a string into proper title caps. Renders a string with Markdown. -``` js +```js <%- markdown(str) %> ``` **Examples:** -``` js +```js <%- markdown('make me **strong**') %> // make me <strong>strong</strong> ``` @@ -424,13 +425,13 @@ Renders a string with Markdown. Renders a string. -``` js +```js <%- render(str, engine, [options]) %> ``` **Examples:** -``` js +```js <%- render('p(class="example") Test', 'pug'); %> // <p class="example">Test</p> ``` @@ -441,13 +442,13 @@ See [Rendering](https://hexo.io/api/rendering) for more details. Wraps text into lines no longer than `length`. `length` is 80 by default. -``` js +```js <%- word_wrap(str, [length]) %> ``` **Examples:** -``` js +```js <%- word_wrap('Once upon a time', 8) %> // Once upon\n a time ``` @@ -456,13 +457,13 @@ Wraps text into lines no longer than `length`. `length` is 80 by default. Truncates text after certain `length`. Default is 30 characters. -``` js +```js <%- truncate(text, [options]) %> ``` **Examples:** -``` js +```js <%- truncate('Once upon a time in a world far far away', {length: 17}) %> // Once upon a ti... @@ -477,13 +478,13 @@ Truncates text after certain `length`. Default is 30 characters. Escapes HTML entities in a string. -``` js +```js <%- escape_html(str) %> ``` **Examples:** -``` js +```js <%- escape_html('<p>Hello "world".</p>') %> // <p>Hello "world".</p> ``` @@ -494,26 +495,26 @@ Escapes HTML entities in a string. Loads other template files. You can define local variables in `locals`. -``` js +```js <%- partial(layout, [locals], [options]) %> ``` -Option | Description | Default ---- | --- | --- -`cache` | Cache contents (Use fragment cache) | `false` -`only` | Strict local variables. Only use variables set in `locals` in templates. | `false` +| Option | Description | Default | +| ------- | ------------------------------------------------------------------------ | ------- | +| `cache` | Cache contents (Use fragment cache) | `false` | +| `only` | Strict local variables. Only use variables set in `locals` in templates. | `false` | ### fragment_cache Caches the contents in a fragment. It saves the contents within a fragment and serves the cache when the next request comes in. -``` js +```js <%- fragment_cache(id, fn); ``` **Examples:** -``` js +```js <%- fragment_cache('header', function(){ return '<header></header>'; }) %> @@ -525,13 +526,13 @@ Caches the contents in a fragment. It saves the contents within a fragment and s Inserts formatted date. `date` can be unix time, ISO string, date object, or [Moment.js] object. `format` is `date_format` setting by default. -``` js +```js <%- date(date, [format]) %> ``` **Examples:** -``` js +```js <%- date(Date.now()) %> // 2013-01-01 @@ -543,13 +544,13 @@ Inserts formatted date. `date` can be unix time, ISO string, date object, or [Mo Inserts date in XML format. `date` can be unix time, ISO string, date object, or [Moment.js] object. -``` js +```js <%- date_xml(date) %> ``` **Examples:** -``` js +```js <%- date_xml(Date.now()) %> // 2013-01-01T00:00:00.000Z ``` @@ -558,13 +559,13 @@ Inserts date in XML format. `date` can be unix time, ISO string, date object, or Inserts formatted time. `date` can be unix time, ISO string, date object, or [Moment.js] object. `format` is `time_format` setting by default. -``` js +```js <%- time(date, [format]) %> ``` **Examples:** -``` js +```js <%- time(Date.now()) %> // 13:05:12 @@ -576,13 +577,13 @@ Inserts formatted time. `date` can be unix time, ISO string, date object, or [Mo Inserts formatted date and time. `date` can be unix time, ISO string, date object, or [Moment.js] object. `format` is `date_format + time_format` setting by default. -``` js +```js <%- full_date(date, [format]) %> ``` **Examples:** -``` js +```js <%- full_date(new Date()) %> // Jan 1, 2013 0:00:00 @@ -600,7 +601,7 @@ Inserts relative time from now. `date` can be unix time, ISO string, date object **Examples:** -``` js +```js <%- relative_date(new Date()) %> // a few seconds ago @@ -618,7 +619,7 @@ Inserts time tag. `date` can be unix time, ISO string, date object, or [Moment.j **Examples:** -``` js +```js <%- time_tag(new Date()) %> // <time datetime="2024-01-22T06:35:31.108Z">2024-01-22</time> @@ -636,25 +637,25 @@ Inserts time tag. `date` can be unix time, ISO string, date object, or [Moment.j Inserts a list of all categories. -``` js +```js <%- list_categories([options]) %> ``` -Option | Description | Default ---- | --- | --- -`orderby` | Order of categories | name -`order` | Sort of order. `1`, `asc` for ascending; `-1`, `desc` for descending | 1 -`show_count` | Display the number of posts for each category | true -`style` | Style to display the category list. `list` displays categories in an unordered list. Use `false` or any other value to disable it. | list -`separator` | Separator between categories. (Only works if `style` is not `list`) | , -`depth` | Levels of categories to be displayed. `0` displays all categories and child categories; `-1` is similar to `0` but displayed in flat; `1` displays only top level categories. | 0 -`class` | Class name of category list. | category -`transform` | The function that changes the display of category name. | -`suffix` | Add a suffix to link. | None +| Option | Description | Default | +| ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | +| `orderby` | Order of categories | name | +| `order` | Sort of order. `1`, `asc` for ascending; `-1`, `desc` for descending | 1 | +| `show_count` | Display the number of posts for each category | true | +| `style` | Style to display the category list. `list` displays categories in an unordered list. Use `false` or any other value to disable it. | list | +| `separator` | Separator between categories. (Only works if `style` is not `list`) | , | +| `depth` | Levels of categories to be displayed. `0` displays all categories and child categories; `-1` is similar to `0` but displayed in flat; `1` displays only top level categories. | 0 | +| `class` | Class name of category list. | category | +| `transform` | The function that changes the display of category name. | +| `suffix` | Add a suffix to link. | None | **Examples:** -``` js +```js <%- list_categories(post.categories, { class: 'post-category', transform(str) { @@ -674,31 +675,31 @@ Option | Description | Default Inserts a list of all tags. -``` js +```js <%- list_tags([options]) %> ``` -Option | Description | Default ---- | --- | --- -`orderby` | Order of categories | name -`order` | Sort of order. `1`, `asc` for ascending; `-1`, `desc` for descending | 1 -`show_count` | Display the number of posts for each tag | true -`style` | Style to display the tag list. `list` displays tags in an unordered list. Use `false` or any other value to disable it. | list -`separator` | Separator between categories. (Only works if `style` is not `list`) | , -`class` | Class name of tag list (string) or customize each tag's class (object, see below). | tag -`transform` | The function that changes the display of tag name. See examples in [list_categories](#list-categories). | -`amount` | The number of tags to display (0 = unlimited) | 0 -`suffix` | Add a suffix to link. | None +| Option | Description | Default | +| ------------ | ----------------------------------------------------------------------------------------------------------------------- | ------- | +| `orderby` | Order of categories | name | +| `order` | Sort of order. `1`, `asc` for ascending; `-1`, `desc` for descending | 1 | +| `show_count` | Display the number of posts for each tag | true | +| `style` | Style to display the tag list. `list` displays tags in an unordered list. Use `false` or any other value to disable it. | list | +| `separator` | Separator between categories. (Only works if `style` is not `list`) | , | +| `class` | Class name of tag list (string) or customize each tag's class (object, see below). | tag | +| `transform` | The function that changes the display of tag name. See examples in [list_categories](#list-categories). | +| `amount` | The number of tags to display (0 = unlimited) | 0 | +| `suffix` | Add a suffix to link. | None | Class advanced customization: -Option | Description | Default ---- | --- | --- -`class.ul` | `<ul>` class name (only for style `list`) | `tag-list` (list style) -`class.li` | `<li>` class name (only for style `list`) | `tag-list-item` (list style) -`class.a` | `<a>` class name | `tag-list-link` (list style) `tag-link` (normal style) -`class.label` | `<span>` class name where the tag label is stored (only for normal style, when `class.label` is set the label is put in a `<span>`) | `tag-label` (normal style) -`class.count` | `<span>` class name where the tag counter is stored (only when `show_count` is `true`) | `tag-list-count` (list style) `tag-count` (normal style) +| Option | Description | Default | +| ------------- | ----------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------- | +| `class.ul` | `<ul>` class name (only for style `list`) | `tag-list` (list style) | +| `class.li` | `<li>` class name (only for style `list`) | `tag-list-item` (list style) | +| `class.a` | `<a>` class name | `tag-list-link` (list style) `tag-link` (normal style) | +| `class.label` | `<span>` class name where the tag label is stored (only for normal style, when `class.label` is set the label is put in a `<span>`) | `tag-label` (normal style) | +| `class.count` | `<span>` class name where the tag counter is stored (only when `show_count` is `true`) | `tag-list-count` (list style) `tag-count` (normal style) | Examples: @@ -713,66 +714,66 @@ Examples: Inserts a list of archives. -``` js +```js <%- list_archives([options]) %> ``` -Option | Description | Default ---- | --- | --- -`type` | Type. This value can be `yearly` or `monthly`. | monthly -`order` | Sort of order. `1`, `asc` for ascending; `-1`, `desc` for descending | 1 -`show_count` | Display the number of posts for each archive | true -`format` | Date format | MMMM YYYY -`style` | Style to display the archive list. `list` displays archives in an unordered list. Use `false` or any other value to disable it. | list -`separator` | Separator between archives. (Only works if `style` is not `list`) | , -`class` | Class name of archive list. | archive -`transform` | The function that changes the display of archive name. See examples in [list_categories](#list-categories). | +| Option | Description | Default | +| ------------ | ------------------------------------------------------------------------------------------------------------------------------- | --------- | +| `type` | Type. This value can be `yearly` or `monthly`. | monthly | +| `order` | Sort of order. `1`, `asc` for ascending; `-1`, `desc` for descending | 1 | +| `show_count` | Display the number of posts for each archive | true | +| `format` | Date format | MMMM YYYY | +| `style` | Style to display the archive list. `list` displays archives in an unordered list. Use `false` or any other value to disable it. | list | +| `separator` | Separator between archives. (Only works if `style` is not `list`) | , | +| `class` | Class name of archive list. | archive | +| `transform` | The function that changes the display of archive name. See examples in [list_categories](#list-categories). | ### list_posts Inserts a list of posts. -``` js +```js <%- list_posts([options]) %> ``` -Option | Description | Default ---- | --- | --- -`orderby` | Order of posts | date -`order` | Sort of order. `1`, `asc` for ascending; `-1`, `desc` for descending | 1 -`style` | Style to display the post list. `list` displays posts in an unordered list. Use `false` or any other value to disable it. | list -`separator` | Separator between posts. (Only works if `style` is not `list`) | , -`class` | Class name of post list. | post -`amount` | The number of posts to display (0 = unlimited) | 6 -`transform` | The function that changes the display of post name. See examples in [list_categories](#list-categories). | +| Option | Description | Default | +| ----------- | ------------------------------------------------------------------------------------------------------------------------- | ------- | +| `orderby` | Order of posts | date | +| `order` | Sort of order. `1`, `asc` for ascending; `-1`, `desc` for descending | 1 | +| `style` | Style to display the post list. `list` displays posts in an unordered list. Use `false` or any other value to disable it. | list | +| `separator` | Separator between posts. (Only works if `style` is not `list`) | , | +| `class` | Class name of post list. | post | +| `amount` | The number of posts to display (0 = unlimited) | 6 | +| `transform` | The function that changes the display of post name. See examples in [list_categories](#list-categories). | ### tagcloud Inserts a tag cloud. -``` js +```js <%- tagcloud([tags], [options]) %> ``` -Option | Description | Default ---- | --- | --- -`min_font` | Minimum font size | 10 -`max_font` | Maximum font size | 20 -`unit` | Unit of font size | px -`amount` | Total amount of tags | unlimited -`orderby` | Order of tags | name -`order` | Sort order. `1`, `asc` as ascending; `-1`, `desc` as descending | 1 -`color` | Colorizes the tag cloud | false -`start_color` | Start color. You can use hex (`#b700ff`), rgba (`rgba(183, 0, 255, 1)`), hsla (`hsla(283, 100%, 50%, 1)`) or [color keywords]. This option only works when `color` is true. | -`end_color` | End color. You can use hex (`#b700ff`), rgba (`rgba(183, 0, 255, 1)`), hsla (`hsla(283, 100%, 50%, 1)`) or [color keywords]. This option only works when `color` is true. | -`class` | Class name prefix of tags -`level` | The number of different class names. This option only works when `class` is set. | 10 -`show_count` (+6.3.0) | Display the number of posts for each tag | false -`count_class` (+6.3.0) | Class name of tag count | count +| Option | Description | Default | +| ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------- | +| `min_font` | Minimum font size | 10 | +| `max_font` | Maximum font size | 20 | +| `unit` | Unit of font size | px | +| `amount` | Total amount of tags | unlimited | +| `orderby` | Order of tags | name | +| `order` | Sort order. `1`, `asc` as ascending; `-1`, `desc` as descending | 1 | +| `color` | Colorizes the tag cloud | false | +| `start_color` | Start color. You can use hex (`#b700ff`), rgba (`rgba(183, 0, 255, 1)`), hsla (`hsla(283, 100%, 50%, 1)`) or [color keywords]. This option only works when `color` is true. | +| `end_color` | End color. You can use hex (`#b700ff`), rgba (`rgba(183, 0, 255, 1)`), hsla (`hsla(283, 100%, 50%, 1)`) or [color keywords]. This option only works when `color` is true. | +| `class` | Class name prefix of tags | +| `level` | The number of different class names. This option only works when `class` is set. | 10 | +| `show_count` (+6.3.0) | Display the number of posts for each tag | false | +| `count_class` (+6.3.0) | Class name of tag count | count | **Examples:** -``` js +```js // Default options <%- tagcloud() %> @@ -786,42 +787,41 @@ Option | Description | Default Inserts a paginator. -``` js +```js <%- paginator(options) %> ``` -Option | Description | Default ---- | --- | --- -`base` | Base URL | / -`format` | URL format | page/%d/ -`total` | The number of pages | 1 -`current` | Current page number | 0 -`prev_text` | The link text of previous page. Works only if `prev_next` is set to true. | Prev -`next_text` | The link text of next page. Works only if `prev_next` is set to true. | Next -`space` | The space text | &hellp; -`prev_next` | Display previous and next links | true -`end_size` | The number of pages displayed on the start and the end side | 1 -`mid_size` | The number of pages displayed between current page, but not including current page | 2 -`show_all` | Display all pages. If this is set to true, `end_size` and `mid_size` will not work | false -`escape` | Escape HTML tags | true -`page_class` (+6.3.0) | Page class name | `page-number` -`current_class` (+6.3.0) | Current page class name | `current` -`space_class` (+6.3.0) | Space class name | `space` -`prev_class` (+6.3.0) | Previous page class name | `extend prev` -`next_class` (+6.3.0) | Next page class name | `extend next` -`force_prev_next` (+6.3.0) | Force display previous and next links | false - +| Option | Description | Default | +| -------------------------- | ---------------------------------------------------------------------------------- | ------------- | +| `base` | Base URL | / | +| `format` | URL format | page/%d/ | +| `total` | The number of pages | 1 | +| `current` | Current page number | 0 | +| `prev_text` | The link text of previous page. Works only if `prev_next` is set to true. | Prev | +| `next_text` | The link text of next page. Works only if `prev_next` is set to true. | Next | +| `space` | The space text | &hellp; | +| `prev_next` | Display previous and next links | true | +| `end_size` | The number of pages displayed on the start and the end side | 1 | +| `mid_size` | The number of pages displayed between current page, but not including current page | 2 | +| `show_all` | Display all pages. If this is set to true, `end_size` and `mid_size` will not work | false | +| `escape` | Escape HTML tags | true | +| `page_class` (+6.3.0) | Page class name | `page-number` | +| `current_class` (+6.3.0) | Current page class name | `current` | +| `space_class` (+6.3.0) | Space class name | `space` | +| `prev_class` (+6.3.0) | Previous page class name | `extend prev` | +| `next_class` (+6.3.0) | Next page class name | `extend next` | +| `force_prev_next` (+6.3.0) | Force display previous and next links | false | **Examples:** -``` js +```js <%- paginator({ prev_text: '<', next_text: '>' }) %> ``` -``` html +```html <!-- Rendered as --> <a href="/1/"><</a> <a href="/1/">1</a> @@ -830,7 +830,7 @@ Option | Description | Default <a href="/3/">></a> ``` -``` js +```js <%- paginator({ prev_text: '<i class="fa fa-angle-left"></i>', next_text: '<i class="fa fa-angle-right"></i>', @@ -838,7 +838,7 @@ Option | Description | Default }) %> ``` -``` html +```html <!-- Rendered as --> <a href="/1/"><i class="fa fa-angle-left"></i></a> <a href="/1/">1</a> @@ -851,33 +851,33 @@ Option | Description | Default Inserts a Google search form. -``` js +```js <%- search_form(options) %> ``` -Option | Description | Default ---- | --- | --- -`class` | The class name of form | search-form -`text` | Search hint word | Search -`button` | Display search button. The value can be a boolean or a string. If the value is a string, it'll be the text of the button. | false +| Option | Description | Default | +| -------- | ------------------------------------------------------------------------------------------------------------------------- | ----------- | +| `class` | The class name of form | search-form | +| `text` | Search hint word | Search | +| `button` | Display search button. The value can be a boolean or a string. If the value is a string, it'll be the text of the button. | false | ### number_format Formats a number. -``` js +```js <%- number_format(number, [options]) %> ``` -Option | Description | Default ---- | --- | --- -`precision` | The precision of number. The value can be `false` or a nonnegative integer. | false -`delimiter` | The thousands delimiter | , -`separator` | The separator between the fractional and integer digits. | . +| Option | Description | Default | +| ----------- | --------------------------------------------------------------------------- | ------- | +| `precision` | The precision of number. The value can be `false` or a nonnegative integer. | false | +| `delimiter` | The thousands delimiter | , | +| `separator` | The separator between the fractional and integer digits. | . | **Examples:** -``` js +```js <%- number_format(12345.67, {precision: 1}) %> // 12,345.68 @@ -898,13 +898,13 @@ Option | Description | Default Inserts [generator tag](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta). -``` js +```js <%- meta_generator() %> ``` **Examples:** -``` js +```js <%- meta_generator() %> // <meta name="generator" content="Hexo 4.0.0"> ``` @@ -913,54 +913,54 @@ Inserts [generator tag](https://developer.mozilla.org/en-US/docs/Web/HTML/Elemen Inserts [Open Graph] data. -``` js +```js <%- open_graph([options]) %> ``` -Option | Description | Default ---- | --- | --- -`title` | Page title (`og:title`) | `page.title` -`type` | Page type (`og:type`) | article(post page)<br>website(non-post page) -`url` | Page URL (`og:url`) | `url` -`image` | Page images (`og:image`) | All images in the content -`author` | Article author (`og:article:author`) | `config.author` -`date` | Article published time (`og:article:published_time`) | Page published time -`updated` | Article modified time (`og:article:modified_time`) | Page modified time -`language` | Article language (`og:locale`) | `page.lang \|\| page.language \|\| config.language` -`site_name` | Site name (`og:site_name`) | `config.title` -`description` | Page description (`og:description`) | Page excerpt or first 200 characters of the content -`twitter_card` | Twitter card type (`twitter:card`) | summary -`twitter_id` | Twitter ID (`twitter:creator`) | -`twitter_site` | Twitter Site (`twitter:site`) | -`twitter_image` | Twitter Image (`twitter:image`) | -`google_plus` | Google+ profile link | -`fb_admins` | Facebook admin ID | -`fb_app_id` | Facebook App ID | +| Option | Description | Default | +| --------------- | ---------------------------------------------------- | --------------------------------------------------- | +| `title` | Page title (`og:title`) | `page.title` | +| `type` | Page type (`og:type`) | article(post page)<br>website(non-post page) | +| `url` | Page URL (`og:url`) | `url` | +| `image` | Page images (`og:image`) | All images in the content | +| `author` | Article author (`og:article:author`) | `config.author` | +| `date` | Article published time (`og:article:published_time`) | Page published time | +| `updated` | Article modified time (`og:article:modified_time`) | Page modified time | +| `language` | Article language (`og:locale`) | `page.lang \|\| page.language \|\| config.language` | +| `site_name` | Site name (`og:site_name`) | `config.title` | +| `description` | Page description (`og:description`) | Page excerpt or first 200 characters of the content | +| `twitter_card` | Twitter card type (`twitter:card`) | summary | +| `twitter_id` | Twitter ID (`twitter:creator`) | +| `twitter_site` | Twitter Site (`twitter:site`) | +| `twitter_image` | Twitter Image (`twitter:image`) | +| `google_plus` | Google+ profile link | +| `fb_admins` | Facebook admin ID | +| `fb_app_id` | Facebook App ID | ### toc Parses all heading tags (h1~h6) in the content and inserts a table of contents. -``` js +```js <%- toc(str, [options]) %> ``` -Option | Description | Default ---- | --- | --- -`class` | Class name | `toc` -`class_item` (+6.3.0) | Class name of item | `${class}-item` -`class_link` (+6.3.0) | Class name of link | `${class}-link` -`class_text` (+6.3.0) | Class name of text | `${class}-text` -`class_child` (+6.3.0) | Class name of child | `${class}-child` -`class_number` (+6.3.0) | Class name of number | `${class}-number` -`class_level` (+6.3.0) | Class name prefix of level | `${class}-level` -`list_number` | Displays list number | true -`max_depth` | Maximum heading depth of generated toc | 6 -`min_depth` | Minimum heading depth of generated toc | 1 +| Option | Description | Default | +| ----------------------- | -------------------------------------- | ----------------- | +| `class` | Class name | `toc` | +| `class_item` (+6.3.0) | Class name of item | `${class}-item` | +| `class_link` (+6.3.0) | Class name of link | `${class}-link` | +| `class_text` (+6.3.0) | Class name of text | `${class}-text` | +| `class_child` (+6.3.0) | Class name of child | `${class}-child` | +| `class_number` (+6.3.0) | Class name of number | `${class}-number` | +| `class_level` (+6.3.0) | Class name prefix of level | `${class}-level` | +| `list_number` | Displays list number | true | +| `max_depth` | Maximum heading depth of generated toc | 6 | +| `min_depth` | Minimum heading depth of generated toc | 1 | **Examples:** -``` js +```js <%- toc(page.content) %> ``` @@ -976,7 +976,7 @@ Please see the below PRs. - https://github.com/hexojs/hexo/pull/4871 - https://github.com/hexojs/hexo-util/pull/269 - https://github.com/hexojs/hexo-renderer-markdown-it/pull/174 -{% endnote %} + {% endnote %} [color keywords]: http://www.w3.org/TR/css3-color/#svg-color [Moment.js]: http://momentjs.com/ diff --git a/source/docs/index.md b/source/docs/index.md index bf858b6ff4..8cd9ef5165 100644 --- a/source/docs/index.md +++ b/source/docs/index.md @@ -1,7 +1,8 @@ --- title: Documentation --- -Welcome to the Hexo documentation. If you encounter any problems when using Hexo, have a look at the [troubleshooting guide](troubleshooting.html), raise an issue on [GitHub](https://github.com/hexojs/hexo/issues) or start a topic on the [Google Group](https://groups.google.com/group/hexo). + +Welcome to the Hexo documentation. If you encounter any problems when using Hexo, have a look at the [troubleshooting guide](troubleshooting.html), raise an issue on [GitHub](https://github.com/hexojs/hexo/issues) or start a topic on the [Google Group](https://groups.google.com/group/hexo). ## What is Hexo? @@ -64,7 +65,7 @@ If you installed Node.js using Snap, you may need to manually run `npm install` Once all the requirements are installed, you can install Hexo with npm: -``` bash +```bash $ npm install -g hexo-cli ``` @@ -72,7 +73,7 @@ $ npm install -g hexo-cli Advanced users may prefer to install and use `hexo` package instead. -``` bash +```bash $ npm install hexo ``` @@ -81,11 +82,11 @@ Once installed, you can run Hexo in two ways: 1. `npx hexo <command>` 2. Linux users can set relative path of `node_modules/` folder: - ``` bash - echo 'PATH="$PATH:./node_modules/.bin"' >> ~/.profile - ``` +```bash +echo 'PATH="$PATH:./node_modules/.bin"' >> ~/.profile +``` - then run Hexo using `hexo <command>` +then run Hexo using `hexo <command>` ### Required Node.js version @@ -95,15 +96,15 @@ Please note we do not provide bugfixes to past versions of Hexo. We highly recommend to always install the [latest version](https://www.npmjs.com/package/hexo?activeTab=versions) of Hexo and the [recommended version](#Requirements) of Node.js, whenever possible. -Hexo version | Minimum (Node.js version) | Less than (Node.js version) ---- | --- | --- -7.0+ | 14.0.0 | latest -6.2+ | 12.13.0 | latest -6.0+ | 12.13.0 | 18.5.0 -5.0+ | 10.13.0 | 12.0.0 -4.1 - 4.2 | 8.10 | 10.0.0 -4.0 | 8.6 | 8.10.0 -3.3 - 3.9 | 6.9 | 8.0.0 -3.2 - 3.3 | 0.12 | unknown -3.0 - 3.1 | 0.10 or iojs | unknown -0.0.1 - 2.8 | 0.10 | unknown +| Hexo version | Minimum (Node.js version) | Less than (Node.js version) | +| ------------ | ------------------------- | --------------------------- | +| 7.0+ | 14.0.0 | latest | +| 6.2+ | 12.13.0 | latest | +| 6.0+ | 12.13.0 | 18.5.0 | +| 5.0+ | 10.13.0 | 12.0.0 | +| 4.1 - 4.2 | 8.10 | 10.0.0 | +| 4.0 | 8.6 | 8.10.0 | +| 3.3 - 3.9 | 6.9 | 8.0.0 | +| 3.2 - 3.3 | 0.12 | unknown | +| 3.0 - 3.1 | 0.10 or iojs | unknown | +| 0.0.1 - 2.8 | 0.10 | unknown | diff --git a/source/docs/internationalization.md b/source/docs/internationalization.md index 718050abd5..21df389627 100644 --- a/source/docs/internationalization.md +++ b/source/docs/internationalization.md @@ -1,9 +1,10 @@ --- title: Internationalization (i18n) --- + You can use internationalization to present your site in different languages. The default language is set by modifying the `language` setting in `_config.yml`. You can also set multiple languages and modify the order of default languages. -``` yaml +```yaml language: zh-tw language: @@ -19,7 +20,7 @@ Language files can be YAML or JSON files. You should put them into the `language Use `__` or `_p` helpers in templates to get the translated strings. The former is for normal usage and the latter is for plural strings. For example: -``` yaml en.yml +```yaml en.yml index: title: Home add: Add @@ -29,7 +30,7 @@ index: other: %d videos ``` -``` js +```js <%= __('index.title') %> // Home @@ -41,13 +42,13 @@ index: You can set the language of pages in front-matter, or modify the `i18n_dir` setting in `_config.yml` to enable automatic detection by Hexo. -``` yaml +```yaml i18n_dir: :lang ``` The default value of `i18n_dir` setting is `:lang`, which means that Hexo will detect the language within the first segment of URL. For example: -``` plain +```plain /index.html => en /archives/index.html => en /zh-tw/index.html => zh-tw diff --git a/source/docs/migration.md b/source/docs/migration.md index 7212999485..a240934dc1 100644 --- a/source/docs/migration.md +++ b/source/docs/migration.md @@ -1,17 +1,18 @@ --- title: Migration --- + ## RSS First, install the `hexo-migrator-rss` plugin. -``` bash +```bash $ npm install hexo-migrator-rss --save ``` Once the plugin is installed, run the following command to migrate all posts from RSS. `source` can be a file path or URL. -``` bash +```bash $ hexo migrate rss <source> ``` @@ -21,7 +22,7 @@ Move all files in the Jekyll `_posts` folder to the `source/_posts` folder. Modify the `new_post_name` setting in `_config.yml`: -``` yaml +```yaml new_post_name: :year-:month-:day-:title.md ``` @@ -31,7 +32,7 @@ Move all files in the Octopress `source/_posts` folder to `source/_posts` Modify the `new_post_name` setting in `_config.yml`: -``` yaml +```yaml new_post_name: :year-:month-:day-:title.md ``` @@ -39,7 +40,7 @@ new_post_name: :year-:month-:day-:title.md First, install the `hexo-migrator-wordpress` plugin. -``` bash +```bash $ npm install hexo-migrator-wordpress --save ``` @@ -47,7 +48,7 @@ Export your WordPress site by going to "Tools" → "Export" → "WordPress" in t Now run: -``` bash +```bash $ hexo migrate wordpress <source> ``` diff --git a/source/docs/one-command-deployment.md b/source/docs/one-command-deployment.md index aaeec8ddad..6f72dd933f 100644 --- a/source/docs/one-command-deployment.md +++ b/source/docs/one-command-deployment.md @@ -21,10 +21,10 @@ You can use multiple deployers. Hexo will execute each deployer in order. ```yaml deploy: -- type: git - repo: -- type: heroku - repo: + - type: git + repo: + - type: heroku + repo: ``` Refer to the [Plugins](https://hexo.io/plugins/) list for more deployment plugins. @@ -47,17 +47,17 @@ deploy: message: [message] ``` -Option | Description | Default ---- | --- | --- -`repo` | URL of the target repository | -`branch` | Branch name. | `gh-pages` (GitHub)<br>`coding-pages` (Coding.net)<br>`master` (others) -`message` | Customize commit message. | `Site updated: {% raw %}{{ now('YYYY-MM-DD HH:mm:ss') }}{% endraw %}` -`token` | Optional token value to authenticate with the repo. Prefix with `$` to read token from environment variable +| Option | Description | Default | +| --------- | ----------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- | +| `repo` | URL of the target repository | +| `branch` | Branch name. | `gh-pages` (GitHub)<br>`coding-pages` (Coding.net)<br>`master` (others) | +| `message` | Customize commit message. | `Site updated: {% raw %}{{ now('YYYY-MM-DD HH:mm:ss') }}{% endraw %}` | +| `token` | Optional token value to authenticate with the repo. Prefix with `$` to read token from environment variable | 3. Deploy your site `hexo clean && hexo deploy`. - - You will be prompted with username and password of the target repository, unless you authenticate with a token or ssh key. - - hexo-deployer-git does not store your username and password. Use [git-credential-cache](https://git-scm.com/docs/git-credential-cache) to store them temporarily. +- You will be prompted with username and password of the target repository, unless you authenticate with a token or ssh key. +- hexo-deployer-git does not store your username and password. Use [git-credential-cache](https://git-scm.com/docs/git-credential-cache) to store them temporarily. 4. Navigate to your repository settings and change the "Pages" branch to `gh-pages` (or the branch specified in your config). The deployed site should be live on the link shown on the "Pages" setting. @@ -173,15 +173,15 @@ deploy: verbose: [true|false] ``` -| Option | Description | Default | -| ------------- | ----------------------------------------- | ------- | -| `host` | Address of remote host | -| `user` | Username | -| `pass` | Password | -| `remote` | Root directory of remote host | `/` | -| `port` | Port | 21 | -| `clear` | Remove all files and directories from the remote directory before upload | false -| `verbose` | Display verbose messages | false | +| Option | Description | Default | +| --------- | ------------------------------------------------------------------------ | ------- | +| `host` | Address of remote host | +| `user` | Username | +| `pass` | Password | +| `remote` | Root directory of remote host | `/` | +| `port` | Port | 21 | +| `clear` | Remove all files and directories from the remote directory before upload | false | +| `verbose` | Display verbose messages | false | ## SFTP @@ -217,7 +217,7 @@ deploy: | `agent` | Path to the ssh-agent socket | `$SSH_AUTH_SOCK` | | `remotePath` | Root directory of remote host | `/` | | `forceUpload` | Override existing files | false | -| `concurrency` | Max number of SFTP tasks processed concurrently | 100 | +| `concurrency` | Max number of SFTP tasks processed concurrently | 100 | ## Vercel @@ -279,8 +279,8 @@ After a few moments, your website will be deployed. 2. Modify the configuration. - ``` yaml - deploy: # The root configuration block for all deployers +```yaml +deploy: # The root configuration block for all deployers - type: rss3 endpoint: https://hub.rss3.io privateKey: 47e18d6c386898b424025cd9db446f779ef24ad33a26c499c87bb3d9372540ba @@ -290,15 +290,15 @@ After a few moments, your website will be deployed. api: key: d693df715d3631e489d6 secret: ee8b74626f12b61c1a4bde3b8c331ad390567c86ba779c9b18561ee92c1cbff0 - ``` - -| Parameters | Description | -| ----------------- | ---------------------- | -| `endpoint` | a link to the RSS3 Hub | -| `privateKey` | your private key, 64 bytes | -| `ipfs/deploy` | whether to deploy to IPFS | -| `ipfs/gateway` | IPFS API gateway | -| `ipfs/api/key` | IPFS gateway-related authentication content | +``` + +| Parameters | Description | +| ----------------- | ------------------------------------------- | +| `endpoint` | a link to the RSS3 Hub | +| `privateKey` | your private key, 64 bytes | +| `ipfs/deploy` | whether to deploy to IPFS | +| `ipfs/gateway` | IPFS API gateway | +| `ipfs/api/key` | IPFS gateway-related authentication content | | `ipfs/api/secret` | IPFS gateway-related authentication content | 3. generate static files diff --git a/source/docs/permalinks.md b/source/docs/permalinks.md index df3405595a..dfdda9740c 100644 --- a/source/docs/permalinks.md +++ b/source/docs/permalinks.md @@ -1,84 +1,85 @@ --- title: Permalinks --- + You can specify the permalinks for your site in `_config.yml` or in the front-matter for each post. ### Variables Besides the following variables, you can use any attributes in the permalink except `:path` and `:permalink`. -Variable | Description ---- | --- -`:year` | Published year of posts (4-digit) -`:month` | Published month of posts (2-digit) -`:i_month` | Published month of posts (Without leading zeros) -`:day` | Published day of posts (2-digit) -`:i_day` | Published day of posts (Without leading zeros) -`:hour` | Published hour of posts (2-digit) -`:minute` | Published minute of posts (2-digit) -`:second` | Published second of posts (2-digit) -`:title` | Filename (relative to "source/_posts/" folder) -`:name` | Filename -`:post_title` | Post title -`:id` | Post ID (_not persistent across [cache reset](/docs/commands#clean)_) -`:category` | Categories. If the post is uncategorized, it will use the `default_category` value. -`:hash` | SHA1 hash of filename (same as `:title`) and date (12-hexadecimal) +| Variable | Description | +| ------------- | ----------------------------------------------------------------------------------- | +| `:year` | Published year of posts (4-digit) | +| `:month` | Published month of posts (2-digit) | +| `:i_month` | Published month of posts (Without leading zeros) | +| `:day` | Published day of posts (2-digit) | +| `:i_day` | Published day of posts (Without leading zeros) | +| `:hour` | Published hour of posts (2-digit) | +| `:minute` | Published minute of posts (2-digit) | +| `:second` | Published second of posts (2-digit) | +| `:title` | Filename (relative to "source/\_posts/" folder) | +| `:name` | Filename | +| `:post_title` | Post title | +| `:id` | Post ID (_not persistent across [cache reset](/docs/commands#clean)_) | +| `:category` | Categories. If the post is uncategorized, it will use the `default_category` value. | +| `:hash` | SHA1 hash of filename (same as `:title`) and date (12-hexadecimal) | You can define the default value of each variable in the permalink through the `permalink_defaults` setting: -``` yaml +```yaml permalink_defaults: lang: en ``` ### Examples -``` yaml source/_posts/hello-world.md +```yaml source/_posts/hello-world.md title: Hello World date: 2013-07-14 17:01:34 categories: -- foo -- bar + - foo + - bar ``` -Setting | Result ---- | --- -`:year/:month/:day/:title/` | 2013/07/14/hello-world/ -`:year-:month-:day-:title.html` | 2013-07-14-hello-world.html -`:category/:title/` | foo/bar/hello-world/ -`:title-:hash/` | hello-world-a2c8ac003b43/ +| Setting | Result | +| ------------------------------- | --------------------------- | +| `:year/:month/:day/:title/` | 2013/07/14/hello-world/ | +| `:year-:month-:day-:title.html` | 2013-07-14-hello-world.html | +| `:category/:title/` | foo/bar/hello-world/ | +| `:title-:hash/` | hello-world-a2c8ac003b43/ | -``` yaml source/_posts/lorem/hello-world.md +```yaml source/_posts/lorem/hello-world.md title: Hello World date: 2013-07-14 17:01:34 categories: -- foo -- bar + - foo + - bar ``` -Setting | Result ---- | --- -`:year/:month/:day/:title/` | 2013/07/14/lorem/hello-world/ -`:year/:month/:day/:name/` | 2013/07/14/hello-world/ +| Setting | Result | +| --------------------------- | ----------------------------- | +| `:year/:month/:day/:title/` | 2013/07/14/lorem/hello-world/ | +| `:year/:month/:day/:name/` | 2013/07/14/hello-world/ | ### Multi-language Support To create a multi-language site, you can modify the `new_post_name` and `permalink` settings like this: -``` yaml +```yaml new_post_name: :lang/:title.md permalink: :lang/:title/ ``` When you create a new post, the post will be saved to: -``` bash +```bash $ hexo new "Hello World" --lang tw # => source/_posts/tw/Hello-World.md ``` and the URL will be: -``` plain +```plain http://localhost:4000/tw/hello-world/ ``` diff --git a/source/docs/server.md b/source/docs/server.md index 7d60ad03f7..06b319560e 100644 --- a/source/docs/server.md +++ b/source/docs/server.md @@ -1,23 +1,24 @@ --- title: Server --- + ## [hexo-server] With the release of Hexo 3, the server has been separated from the main module. To start using the server, you will first have to install [hexo-server]. -``` bash +```bash $ npm install hexo-server --save ``` Once the server has been installed, run the following command to start the server. Your website will run at `http://localhost:4000` by default. When the server is running, Hexo will watch for file changes and update automatically so it's not necessary to manually restart the server. -``` bash +```bash $ hexo server ``` If you want to change the port or if you're encountering `EADDRINUSE` errors, use the `-p` option to set a different port. -``` bash +```bash $ hexo server -p 5000 ``` @@ -25,7 +26,7 @@ $ hexo server -p 5000 In static mode, only files in the `public` folder will be served and file watching is disabled. You have to run `hexo generate` before starting the server. Usually used in production. -``` bash +```bash $ hexo server -s ``` @@ -33,7 +34,7 @@ $ hexo server -s Hexo runs the server at `0.0.0.0` by default. You can override the default IP setting. -``` bash +```bash $ hexo server -i 192.168.1.1 ``` diff --git a/source/docs/setup.md b/source/docs/setup.md index 58735b96c8..6a04acd7d7 100644 --- a/source/docs/setup.md +++ b/source/docs/setup.md @@ -6,7 +6,7 @@ title: Setup Once Hexo is installed, run the following commands to initialize Hexo in the target `<folder>`. -``` bash +```bash $ hexo init <folder> $ cd <folder> $ npm install @@ -14,7 +14,7 @@ $ npm install Once initialized, here's what your project folder will look like: -``` plain +```plain . ├── _config.yml ├── package.json @@ -25,7 +25,7 @@ Once initialized, here's what your project folder will look like: └── themes ``` -### _config.yml +### \_config.yml Site [configuration](configuration.html) file. You can configure most settings here. @@ -33,7 +33,7 @@ Site [configuration](configuration.html) file. You can configure most settings h Application data. The [EJS](https://ejs.co/), [Stylus](http://learnboost.github.io/stylus/) and [Markdown](http://daringfireball.net/projects/markdown/) renderers are installed by default. If you want, you can uninstall them later. -``` json package.json +```json package.json { "name": "hexo-site", "version": "0.0.0", diff --git a/source/docs/syntax-highlight.md b/source/docs/syntax-highlight.md index 4404ebaace..1fa7bf7f18 100644 --- a/source/docs/syntax-highlight.md +++ b/source/docs/syntax-highlight.md @@ -17,7 +17,7 @@ code snippet code snippet {% endcode %} -``` [language] [title] [url] [link text] [additional options] +```[language] [title] [url] [link text] [additional options] code snippet ``` ```` @@ -37,7 +37,7 @@ highlight: auto_detect: false line_number: true line_threshold: 0 - tab_replace: '' + tab_replace: "" exclude_languages: - example wrap: true @@ -47,7 +47,7 @@ prismjs: preprocess: true line_number: true line_threshold: 0 - tab_replace: '' + tab_replace: "" ``` v7.0.0+: @@ -59,7 +59,7 @@ highlight: auto_detect: false line_number: true line_threshold: 0 - tab_replace: '' + tab_replace: "" exclude_languages: - example wrap: true @@ -68,7 +68,7 @@ prismjs: preprocess: true line_number: true line_threshold: 0 - tab_replace: '' + tab_replace: "" ``` The YAML above is Hexo's default configuration. @@ -89,7 +89,7 @@ v7.0.0+: ```yaml # _config.yml -syntax_highlighter: # empty +syntax_highlighter: # empty ``` When both `highlight.enable` and `prismjs.enable` are `false` (below v7.0.0) or `syntax_highlighter` is empty (v7.0.0+), the output HTML of the code block is controlled by the corresponding renderer. For example, [`marked.js`](https://github.com/markedjs/marked) (used by [`hexo-renderer-marked`](https://github.com/hexojs/hexo-renderer-marked), the default markdown renderer of Hexo) will add the language code to the `class` of `<code>`: @@ -119,7 +119,7 @@ highlight: auto_detect: false line_number: true line_threshold: 0 - tab_replace: ' ' + tab_replace: " " exclude_languages: - example wrap: true @@ -137,7 +137,7 @@ highlight: auto_detect: false line_number: true line_threshold: 0 - tab_replace: ' ' + tab_replace: " " exclude_languages: - example wrap: true @@ -166,18 +166,18 @@ Hexo adds line number by wrapping output inside `<figure>` and `<table>`: ```html <figure class="highlight yaml"> -<table> -<tbody> -<tr> - <td class="gutter"> - <pre><span class="line">1</span><br></pre> - </td> - <td class="code"> - <pre><span class="line"><span class="attr">hello:</span><span class="string">hexo</span></span><br></pre> - </td> -</tr> -</tbody> -</table> + <table> + <tbody> + <tr> + <td class="gutter"> + <pre><span class="line">1</span><br></pre> + </td> + <td class="code"> + <pre><span class="line"><span class="attr">hello:</span><span class="string">hexo</span></span><br></pre> + </td> + </tr> + </tbody> + </table> </figure> ``` @@ -238,7 +238,7 @@ prismjs: preprocess: true line_number: true line_threshold: 0 - tab_replace: '' + tab_replace: "" ``` v7.0.0+: @@ -250,7 +250,7 @@ prismjs: preprocess: true line_number: true line_threshold: 0 - tab_replace: '' + tab_replace: "" ``` Prismjs is disabled by default. You should set `highlight.enable` to `false` (below v7.0.0) or set `syntax_highlighter` to `prismjs` (v7.0.0+) before enabling prismjs. diff --git a/source/docs/tag-plugins.md b/source/docs/tag-plugins.md index 979602614d..893dcb6c55 100644 --- a/source/docs/tag-plugins.md +++ b/source/docs/tag-plugins.md @@ -1,6 +1,7 @@ --- title: Tag Plugins --- + Tag plugins are different from post tags. They are ported from Octopress and provide a useful way for you to quickly add specific content to your posts. Although you can write your posts in any format, the tag plugins will always be available and syntax remains the same. @@ -85,14 +86,14 @@ code snippet Specify additional options in `option:value` format, e.g. `line_number:false first_line:5`. -Extra Options | Description | Default ---- | --- | --- -`line_number` | Show line number | `true` -`line_threshold` | Only show line numbers as long as the numbers of lines of the code block exceed such threshold. | `0` | -`highlight` | Enable code highlighting | `true` -`first_line` | Specify the first line number | `1` -`mark` | Line highlight specific line(s), each value separated by a comma. Specify the number range using a dash<br>Example: `mark:1,4-7,10` will mark lines 1, 4 to 7 and 10. | -`wrap` | Wrap the code block in [`<table>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table) | `true` +| Extra Options | Description | Default | +| ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| `line_number` | Show line number | `true` | +| `line_threshold` | Only show line numbers as long as the numbers of lines of the code block exceed such threshold. | `0` | +| `highlight` | Enable code highlighting | `true` | +| `first_line` | Specify the first line number | `1` | +| `mark` | Line highlight specific line(s), each value separated by a comma. Specify the number range using a dash<br>Example: `mark:1,4-7,10` will mark lines 1, 4 to 7 and 10. | +| `wrap` | Wrap the code block in [`<table>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table) | `true` | ### Examples @@ -142,7 +143,7 @@ _.compact([0, 1, false, 2, '', 3]); ``` {% codeblock _.compact http://underscorejs.org/#compact Underscore.js %} -_.compact([0, 1, false, 2, '', 3]); +\_.compact([0, 1, false, 2, '', 3]); => [1, 2, 3] {% endcodeblock %} @@ -151,9 +152,9 @@ _.compact([0, 1, false, 2, '', 3]); This is identical to using a code block, but instead uses three backticks to delimit the block. {% raw %} -``` [language] [title] [url] [link text] +`` [language] [title] [url] [link text] code snippet -``` +`` {% endraw %} ## Pull Quote @@ -370,32 +371,32 @@ _hexo-renderer-marked 3.1.0+ can (optionally) resolves the post's path of an ima `{% asset_img foo.jpg %}` -``` html -<img src="/2020/01/02/hello/foo.jpg"> +```html +<img src="/2020/01/02/hello/foo.jpg" /> ``` **Custom class** `{% asset_img post-image foo.jpg %}` -``` html -<img src="/2020/01/02/hello/foo.jpg" class="post-image"> +```html +<img src="/2020/01/02/hello/foo.jpg" class="post-image" /> ``` **Display size** `{% asset_img foo.jpg 500 400 %}` -``` html -<img src="/2020/01/02/hello/foo.jpg" width="500" height="400"> +```html +<img src="/2020/01/02/hello/foo.jpg" width="500" height="400" /> ``` **Title & Alt** `{% asset_img foo.jpg "lorem ipsum'dolor'" %}` -``` html -<img src="/2020/01/02/hello/foo.jpg" title="lorem ipsum" alt="dolor"> +```html +<img src="/2020/01/02/hello/foo.jpg" title="lorem ipsum" alt="dolor" /> ``` ## URL @@ -410,23 +411,23 @@ Returns a url with the root path prefixed. Output is encoded automatically. **Examples:** -``` yml +```yml _config.yml root: /blog/ # example ``` -``` +``` {% url_for blog index.html %} ``` -``` html +```html <a href="/blog/index.html">blog</a> ``` Relative link, follows `relative_link` option by default e.g. post/page path is '/foo/bar/index.html' -``` yml +```yml _config.yml relative_link: true ``` @@ -435,7 +436,7 @@ relative_link: true {% url_for blog index.html %} ``` -``` html +```html <a href="../../index.html">blog</a> ``` @@ -445,7 +446,7 @@ You could also disable it to output a non-relative link, even when `relative_lin {% url_for blog index.html false %} ``` -``` html +```html <a href="/index.html">blog</a> ``` @@ -459,7 +460,7 @@ Returns a url with the `config.url` prefixed. Output is encoded automatically. **Examples:** -``` yml +```yml _config.yml url: https://example.com/blog # example ``` @@ -468,7 +469,7 @@ url: https://example.com/blog # example {% full_url_for index /a/path %} ``` -``` html +```html <a href="https://example.com/blog/a/path">index</a> ``` diff --git a/source/docs/templates.md b/source/docs/templates.md index 1ba98f4b8a..c97d1063fc 100644 --- a/source/docs/templates.md +++ b/source/docs/templates.md @@ -1,40 +1,45 @@ --- title: Templates --- + Templates define the presentation of your website by describing what each page should look like. The table below shows the corresponding template for every available page. At the very least, a theme should contain an `index` template. {% youtube mb65bQ4iUc4 %} -Template | Page | Fallback ---- | --- | --- -`index` | Home page | -`post` | Posts | `index` -`page` | Pages | `index` -`archive` | Archives | `index` -`category` | Category archives | `archive` -`tag` | Tag archives | `archive` +| Template | Page | Fallback | +| ---------- | ----------------- | --------- | +| `index` | Home page | +| `post` | Posts | `index` | +| `page` | Pages | `index` | +| `archive` | Archives | `index` | +| `category` | Category archives | `archive` | +| `tag` | Tag archives | `archive` | ## Layouts When pages share a similar structure - for instance, when two templates have both a header and a footer - you can consider using a `layout` to declare these structural similarities. Every layout file should contain a `body` variable to display the contents of the template in question. For example: -``` html index.ejs +```html index.ejs index ``` -``` html layout.ejs -<!DOCTYPE html> +```html layout.ejs +<!doctype html> <html> - <body><%- body %></body> + <body> + <%- body %> + </body> </html> ``` yields: -``` html -<!DOCTYPE html> +```html +<!doctype html> <html> - <body>index</body> + <body> + index + </body> </html> ``` @@ -44,18 +49,18 @@ By default, the `layout` template is used by all other templates. You can specif Partials are useful for sharing components between your templates. Typical examples include headers, footers or sidebars. You may want to put your partials in separate files to make maintaining your website significantly more convenient. For example: -``` html partial/header.ejs +```html partial/header.ejs <h1 id="logo"><%= config.title %></h1> ``` -``` html index.ejs +```html index.ejs <%- partial('partial/header') %> <div id="content">Home page</div> ``` yields: -``` html +```html <h1 id="logo">My Site</h1> <div id="content">Home page</div> ``` @@ -64,18 +69,18 @@ yields: You can define local variables in templates and use them in other templates. -``` html partial/header.ejs +```html partial/header.ejs <h1 id="logo"><%= title %></h1> ``` -``` html index.ejs +```html index.ejs <%- partial('partial/header', {title: 'Hello World'}) %> <div id="content">Home page</div> ``` yields: -``` html +```html <h1 id="logo">Hello World</h1> <div id="content">Home page</div> ``` @@ -88,7 +93,7 @@ This feature was borrowed from [Ruby on Rails](http://guides.rubyonrails.org/cac Fragment caching is best used for headers, footers, sidebars or other static content that is unlikely to change from template to template. For example: -``` js +```js <%- fragment_cache('header', function(){ return '<header></header>'; }); @@ -96,7 +101,7 @@ Fragment caching is best used for headers, footers, sidebars or other static con Though it may be easier to use partials: -``` js +```js <%- partial('header', {}, {cache: true}); ``` diff --git a/source/docs/themes.md b/source/docs/themes.md index 4c634892bf..b2a655491e 100644 --- a/source/docs/themes.md +++ b/source/docs/themes.md @@ -73,7 +73,7 @@ When you have finished building your theme, you can publish it to the [theme lis - one_column ``` -5. Add a screenshot (with the same name as the theme) to `source/themes/screenshots`. It must be a 800*500px PNG. +5. Add a screenshot (with the same name as the theme) to `source/themes/screenshots`. It must be a 800\*500px PNG. 6. Push the branch. 7. Create a pull request and describe the change. diff --git a/source/docs/troubleshooting.md b/source/docs/troubleshooting.md index 6e3417c624..32304df39f 100644 --- a/source/docs/troubleshooting.md +++ b/source/docs/troubleshooting.md @@ -1,18 +1,19 @@ --- title: Troubleshooting --- + In case you're experiencing problems with using Hexo, here is a list of solutions to some frequently encountered issues. If this page doesn't help you solve your problem, try doing a search on [GitHub](https://github.com/hexojs/hexo/issues) or our [Google Group](https://groups.google.com/group/hexo). ## YAML Parsing Error -``` plain +```plain JS-YAML: incomplete explicit mapping pair; a key node is missed at line 18, column 29: last_updated: Last updated: %s ``` Wrap the string with quotations if it contains colons. -``` plain +```plain JS-YAML: bad indentation of a mapping entry at line 18, column 31: last_updated:"Last updated: %s" ``` @@ -23,13 +24,13 @@ You can see [YAML Spec](http://www.yaml.org/spec/1.2/spec.html) for more info. ## EMFILE Error -``` plain +```plain Error: EMFILE, too many open files ``` Though Node.js has non-blocking I/O, the maximum number of synchronous I/O is still limited by the system. You may come across an EMFILE error when trying to generate a large number of files. You can try to run the following command to increase the number of allowed synchronous I/O operations. -``` bash +```bash $ ulimit -n 10000 ``` @@ -37,7 +38,7 @@ $ ulimit -n 10000 If you encounter the following error: -``` bash +```bash $ ulimit -n 10000 ulimit: open files: cannot modify limit: Operation not permitted ``` @@ -48,23 +49,23 @@ To override the limit: 1. Add the following line to "/etc/security/limits.conf": - ``` - * - nofile 10000 +``` +* - nofile 10000 - # '*' applies to all users and '-' set both soft and hard limits - ``` +# '*' applies to all users and '-' set both soft and hard limits +``` - * The above setting may not apply in some cases, ensure "/etc/pam.d/login" and "/etc/pam.d/lightdm" have the following line. (Ignore this step if those files do not exist) +- The above setting may not apply in some cases, ensure "/etc/pam.d/login" and "/etc/pam.d/lightdm" have the following line. (Ignore this step if those files do not exist) - ``` - session required pam_limits.so - ``` +``` +session required pam_limits.so +``` 2. If you are on a [systemd-based](https://en.wikipedia.org/wiki/Systemd#Adoption) distribution, systemd may override "limits.conf". To set the limit in systemd, add the following line in "/etc/systemd/system.conf" and "/etc/systemd/user.conf": - ``` - DefaultLimitNOFILE=10000 - ``` +``` +DefaultLimitNOFILE=10000 +``` 3. Reboot @@ -88,7 +89,7 @@ Increase Node.js heap memory size by changing the first line of `hexo-cli` (`whi ### RPC failed -``` plain +```plain error: RPC failed; result=22, HTTP code = 403 fatal: 'username.github.io' does not appear to be a git repository @@ -113,19 +114,19 @@ To fix this, try ## Server Problems -``` plain +```plain Error: listen EADDRINUSE ``` You may have started two Hexo servers at the same time or there might be another application using the same port. Try to modify the `port` setting or start the Hexo server with the `-p` flag. -``` bash +```bash $ hexo server -p 5000 ``` ## Plugin Installation Problems -``` plain +```plain npm ERR! node-waf configure build ``` @@ -160,7 +161,7 @@ Hexo uses [Warehouse] for its data model. It's not an array so you may have to t Some data cannot be updated, or the newly generated files are identical to those of the last version. Clean the cache and try again. -``` bash +```bash $ hexo clean ``` @@ -178,7 +179,7 @@ When you can't get any command except `help`, `init` and `version` to work and y ## Escape Contents -Hexo uses [Nunjucks] to render posts ([Swig] was used in the older version, which shares a similar syntax). Content wrapped with `{{ }}` or `{% %}` will get parsed and may cause problems. You can skip the parsing by wrapping it with the [`raw`](/docs/tag-plugins#Raw) tag plugin, a single backtick ```` `{{ }}` ```` or a triple backtick. +Hexo uses [Nunjucks] to render posts ([Swig] was used in the older version, which shares a similar syntax). Content wrapped with `{{ }}` or `{% %}` will get parsed and may cause problems. You can skip the parsing by wrapping it with the [`raw`](/docs/tag-plugins#Raw) tag plugin, a single backtick `` `{{ }}` `` or a triple backtick. Alternatively, Nunjucks tags can be disabled through the renderer's option (if supported), [API](/api/renderer#Disable-Nunjucks-tags) or [front-matter](/docs/front-matter). ``` @@ -219,7 +220,7 @@ Error: watch /path/to/hexo/theme/ EMPERM Unfortunately, WSL does not currently support filesystem watchers. Therefore, the live updating feature of hexo's server is currently unavailable. You can still run the server from a WSL environment by first generating the files and then running it as a static server: -``` sh +```sh $ hexo generate $ hexo server -s ``` @@ -236,9 +237,12 @@ Template render error: (unknown path) ``` Possible cause: + - There are some unrecognizable words in your file, e.g. invisible zero width characters. - Incorrect use or limitation of [tag plugin](/docs/tag-plugins). - * Block-style tag plugin with content is not enclosed with `{% endplugin_name %}` + + - Block-style tag plugin with content is not enclosed with `{% endplugin_name %}` + ``` # Incorrect {% codeblock %} @@ -254,7 +258,9 @@ Possible cause: fn() {% endcodeblock %} ``` - * Having Nunjucks-like syntax in a tag plugin, e.g. [`{#`](https://mozilla.github.io/nunjucks/templating.html#comments). A workaround for this example is to use [triple backtick](/docs/tag-plugins#Backtick-Code-Block) instead. [Escape Contents](/docs/troubleshooting#Escape-Contents) section has more details. + + - Having Nunjucks-like syntax in a tag plugin, e.g. [`{#`](https://mozilla.github.io/nunjucks/templating.html#comments). A workaround for this example is to use [triple backtick](/docs/tag-plugins#Backtick-Code-Block) instead. [Escape Contents](/docs/troubleshooting#Escape-Contents) section has more details. + ``` {% codeblock lang:bash %} Size of array is ${#ARRAY} @@ -269,16 +275,19 @@ Upgrading to `hexo^6.1.0` from an older version may cause the following error wh YAMLException: Specified list of YAML types (or a single Type object) contains a non-Type object. at ... ``` - -This may be caused by an incorrect dependency(i.e. `js-yaml`) setting that can't be solved automatically by the package manager, and you may have to update it manually running: + +This may be caused by an incorrect dependency(i.e. `js-yaml`) setting that can't be solved automatically by the package manager, and you may have to update it manually running: ```sh $ npm install js-yaml@latest ``` + or + ```sh $ yarn add js-yaml@latest ``` + if you use `yarn`. [Warehouse]: https://github.com/hexojs/warehouse diff --git a/source/docs/variables.md b/source/docs/variables.md index c63a8bc0e4..0c648b704c 100644 --- a/source/docs/variables.md +++ b/source/docs/variables.md @@ -6,15 +6,15 @@ title: Variables ### Global Variables -Variable | Description | Type ---- | --- | --- -`site` | Sitewide information. | `object`; see [Site Variables] -`page` | Page specific information and custom variables set in front-matter. | `object`; see [Page Variables] -`config` | Site configuration. | `object` (your site's _config file) -`theme` | Theme configuration. Inherits from site configuration. | `object` (your theme's _config file) -`path` | Path of current page | `string` -`url` | Full URL of current page | `string` -`env` | Environment variables | ??? +| Variable | Description | Type | +| -------- | ------------------------------------------------------------------- | ------------------------------------- | +| `site` | Sitewide information. | `object`; see [Site Variables] | +| `page` | Page specific information and custom variables set in front-matter. | `object`; see [Page Variables] | +| `config` | Site configuration. | `object` (your site's \_config file) | +| `theme` | Theme configuration. Inherits from site configuration. | `object` (your theme's \_config file) | +| `path` | Path of current page | `string` | +| `url` | Full URL of current page | `string` | +| `env` | Environment variables | ??? | {% note warn %} Lodash has been removed from global variables since Hexo 5.0.0. [You-Dont-Need-Lodash-Underscore](https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore) might be helpful for your migration. @@ -22,79 +22,79 @@ Lodash has been removed from global variables since Hexo 5.0.0. [You-Dont-Need-L ### Site Variables -Variable | Description | Type ---- | --- | --- -`site.posts` | All posts | `array` of `post` objects -`site.pages` | All pages | `array` of `page` objects -`site.categories` | All categories | `array` of ??? -`site.tags` | All tags | `array` of ??? +| Variable | Description | Type | +| ----------------- | -------------- | ------------------------- | +| `site.posts` | All posts | `array` of `post` objects | +| `site.pages` | All pages | `array` of `page` objects | +| `site.categories` | All categories | `array` of ??? | +| `site.tags` | All tags | `array` of ??? | ### Page Variables **Article (`page`)** -Variable | Description | Type ---- | --- | --- -`page.title` | Article title | `string` -`page.date` | Article created date | [Moment.js] object -`page.updated` | Article last updated date | [Moment.js] object -`page.comments` | Comment enabled or not | `boolean` -`page.layout` | Layout name | `string` -`page.content` | The full processed content of the article | `string` -`page.excerpt` | Article excerpt | `string` -`page.more` | Contents except article excerpt | `string` -`page.source` | The path of the source file | `string` -`page.full_source` | Full path of the source file | `string` -`page.path` | The URL of the article without root URL. We usually use `url_for(page.path)` in theme. | `string` -`page.permalink` | Full (encoded) URL of the article | `string` -`page.prev` | The previous post, `null` if the post is the first post | ??? -`page.next` | The next post, `null` if the post is the last post | ??? -`page.raw` | The raw data of the article | ??? -`page.photos` | The photos of the article (Used in gallery posts) | array of ??? -`page.link` | The external link of the article (Used in link posts) | `string` +| Variable | Description | Type | +| ------------------ | -------------------------------------------------------------------------------------- | ------------------ | +| `page.title` | Article title | `string` | +| `page.date` | Article created date | [Moment.js] object | +| `page.updated` | Article last updated date | [Moment.js] object | +| `page.comments` | Comment enabled or not | `boolean` | +| `page.layout` | Layout name | `string` | +| `page.content` | The full processed content of the article | `string` | +| `page.excerpt` | Article excerpt | `string` | +| `page.more` | Contents except article excerpt | `string` | +| `page.source` | The path of the source file | `string` | +| `page.full_source` | Full path of the source file | `string` | +| `page.path` | The URL of the article without root URL. We usually use `url_for(page.path)` in theme. | `string` | +| `page.permalink` | Full (encoded) URL of the article | `string` | +| `page.prev` | The previous post, `null` if the post is the first post | ??? | +| `page.next` | The next post, `null` if the post is the last post | ??? | +| `page.raw` | The raw data of the article | ??? | +| `page.photos` | The photos of the article (Used in gallery posts) | array of ??? | +| `page.link` | The external link of the article (Used in link posts) | `string` | **Post (`post`):** Same as `page` layout but add the following variables. -Variable | Description | Type ---- | --- | --- -`page.published` | True if the post is not a draft | `boolean` -`page.categories` | All categories of the post | `array` of ??? -`page.tags` | All tags of the post | `array` of ??? +| Variable | Description | Type | +| ----------------- | ------------------------------- | -------------- | +| `page.published` | True if the post is not a draft | `boolean` | +| `page.categories` | All categories of the post | `array` of ??? | +| `page.tags` | All tags of the post | `array` of ??? | **Home (`index`)** -Variable | Description | Type ---- | --- | --- -`page.per_page` | Posts displayed per page | `number` -`page.total` | Total number of pages | `number` -`page.current` | Current page number | `number` -`page.current_url` | The URL of current page | `string` -`page.posts` | Posts in this page ([Data Model](https://hexojs.github.io/warehouse/)) | `object` -`page.prev` | Previous page number. `0` if the current page is the first. | `number` -`page.prev_link` | The URL of previous page. `''` if the current page is the first. | `string` -`page.next` | Next page number. `0` if the current page is the last. | `number` -`page.next_link` | The URL of next page. `''` if the current page is the last. | `string` -`page.path` | The URL of current page without root URL. We usually use `url_for(page.path)` in theme. | `string` +| Variable | Description | Type | +| ------------------ | --------------------------------------------------------------------------------------- | -------- | +| `page.per_page` | Posts displayed per page | `number` | +| `page.total` | Total number of pages | `number` | +| `page.current` | Current page number | `number` | +| `page.current_url` | The URL of current page | `string` | +| `page.posts` | Posts in this page ([Data Model](https://hexojs.github.io/warehouse/)) | `object` | +| `page.prev` | Previous page number. `0` if the current page is the first. | `number` | +| `page.prev_link` | The URL of previous page. `''` if the current page is the first. | `string` | +| `page.next` | Next page number. `0` if the current page is the last. | `number` | +| `page.next_link` | The URL of next page. `''` if the current page is the last. | `string` | +| `page.path` | The URL of current page without root URL. We usually use `url_for(page.path)` in theme. | `string` | **Archive (`archive`):** Same as `index` layout but add the following variables. -Variable | Description | Type ---- | --- | --- -`page.archive` | Equals `true` | `boolean` -`page.year` | Archive year (4-digit) | `number` -`page.month` | Archive month (2-digit without leading zeros) | `number` +| Variable | Description | Type | +| -------------- | --------------------------------------------- | --------- | +| `page.archive` | Equals `true` | `boolean` | +| `page.year` | Archive year (4-digit) | `number` | +| `page.month` | Archive month (2-digit without leading zeros) | `number` | **Category (`category`):** Same as `index` layout but add the following variables. -Variable | Description | Type ---- | --- | --- -`page.category` | Category name | `string` +| Variable | Description | Type | +| --------------- | ------------- | -------- | +| `page.category` | Category name | `string` | **Tag (`tag`):** Same as `index` layout but add the following variables. -Variable | Description | Type ---- | --- | --- -`page.tag` | Tag name | `string` +| Variable | Description | Type | +| ---------- | ----------- | -------- | +| `page.tag` | Tag name | `string` | [Moment.js]: http://momentjs.com/ [Site Variables]: #Site-Variables diff --git a/source/docs/writing.md b/source/docs/writing.md index 6dc3eda58c..14ad1e780b 100644 --- a/source/docs/writing.md +++ b/source/docs/writing.md @@ -6,7 +6,7 @@ title: Writing To create a new post or a new page, you can run the following command: -``` bash +```bash $ hexo new [layout] <title> ``` @@ -16,11 +16,11 @@ $ hexo new [layout] <title> There are three default layouts in Hexo: `post`, `page` and `draft`. Files created by each of them is saved to a different path. Newly created posts are saved to the `source/_posts` folder. -Layout | Path ---- | --- -`post` | `source/_posts` -`page` | `source` -`draft` | `source/_drafts` +| Layout | Path | +| ------- | ---------------- | +| `post` | `source/_posts` | +| `page` | `source` | +| `draft` | `source/_drafts` | {% note tip Disabling layout %} If you don't want an article (post/page) to be processed with a theme, set `layout: false` in its front-matter. Refer to [this section](/docs/front-matter#Layout) for more details. @@ -30,20 +30,20 @@ If you don't want an article (post/page) to be processed with a theme, set `layo By default, Hexo uses the post title as its filename. You can edit the `new_post_name` setting in `_config.yml` to change the default filename. For example, `:year-:month-:day-:title.md` will prefix filenames with the post creation date. You can use the following placeholders: -Placeholder | Description ---- | --- -`:title` | Post title (lower case, with spaces replaced by hyphens) -`:year` | Created year, e.g. `2015` -`:month` | Created month (leading zeros), e.g. `04` -`:i_month` | Created month (no leading zeros), e.g. `4` -`:day` | Created day (leading zeros), e.g. `07` -`:i_day` | Created day (no leading zeros), e.g. `7` +| Placeholder | Description | +| ----------- | -------------------------------------------------------- | +| `:title` | Post title (lower case, with spaces replaced by hyphens) | +| `:year` | Created year, e.g. `2015` | +| `:month` | Created month (leading zeros), e.g. `04` | +| `:i_month` | Created month (no leading zeros), e.g. `4` | +| `:day` | Created day (leading zeros), e.g. `07` | +| `:i_day` | Created day (no leading zeros), e.g. `7` | ## Drafts Previously, we mentioned a special layout in Hexo: `draft`. Posts initialized with this layout are saved to the `source/_drafts` folder. You can use the `publish` command to move drafts to the `source/_posts` folder. `publish` works in a similar way to the `new` command. -``` bash +```bash $ hexo publish [layout] <title> ``` @@ -53,17 +53,17 @@ Drafts are not displayed by default. You can add the `--draft` option when runni When creating posts, Hexo will build files based on the corresponding file in `scaffolds` folder. For example: -``` bash +```bash $ hexo new photo "My Gallery" ``` When you run this command, Hexo will try to find `photo.md` in the `scaffolds` folder and build the post based on it. The following placeholders are available in scaffolds: -Placeholder | Description ---- | --- -`layout` | Layout -`title` | Title -`date` | File created date +| Placeholder | Description | +| ----------- | ----------------- | +| `layout` | Layout | +| `title` | Title | +| `date` | File created date | ## Supported Formats diff --git a/source/ja/api/box.md b/source/ja/api/box.md index c9794b8b14..3147bea113 100644 --- a/source/ja/api/box.md +++ b/source/ja/api/box.md @@ -1,6 +1,7 @@ --- title: ボックス --- + ボックスは指定されたフォルダ内のファイルを処理するために使用されるコンテナです。Hexoでは2種類のボックスが使用されます。`hexo.source`と`hexo.theme`です。前者は`source`フォルダを処理するために、後者は`theme`フォルダを処理するために使用されます。 ## ファイルの読み込み @@ -8,11 +9,11 @@ title: ボックス ボックスはファイルを読み込むために`process`と`watch`の2つの方法を提供します。`process`はフォルダ内のすべてのファイルを読み込みます。`watch`も同様の操作を行いますが、ファイルの変更の監視も開始します。 ```js -box.process().then(function(){ +box.process().then(function () { // ... }); -box.watch().then(function(){ +box.watch().then(function () { // 後で box.unwatch() を呼び出して監視を停止できます。 }); ``` @@ -21,7 +22,7 @@ box.watch().then(function(){ ボックスはパスマッチングのための多くの方法を提供します。正規表現、関数、またはExpressスタイルのパターン文字列を使用できます。例えば: -``` plain +```plain posts/:id => posts/89 posts/*path => posts/2015/title ``` @@ -32,30 +33,30 @@ posts/*path => posts/2015/title プロセッサはボックスの重要な要素であり、ファイルを処理するために使用されます。上記のパスマッチングを使用して、プロセッサが何を処理すべきか、正確に指定できます。新しいプロセッサを`addProcessor`メソッドで登録します。 -``` js -box.addProcessor('posts/:id', function(file){ +```js +box.addProcessor("posts/:id", function (file) { // }); ``` ボックスはマッチしたファイルの内容をプロセッサに渡します。この情報はコールバックの`file`引数から直接読むことができます: -属性 | 説明 ---- | --- -`source` | ファイルの完全なパス -`path` | ファイルのボックスまでの相対パス -`type` | ファイルのタイプ。値は`create`, `update`, `skip`, `delete`があります。 -`params` | パスマッチングからの情報。 +| 属性 | 説明 | +| -------- | ---------------------------------------------------------------------- | +| `source` | ファイルの完全なパス | +| `path` | ファイルのボックスまでの相対パス | +| `type` | ファイルのタイプ。値は`create`, `update`, `skip`, `delete`があります。 | +| `params` | パスマッチングからの情報。 | ボックスはファイルIOを自分で行う必要がないようにいくつかのメソッドも提供しています。 -メソッド | 説明 ---- | --- -`read` | ファイルを読み込む -`readSync` | 同期的にファイルを読み込む -`stat` | ファイルのステータスを読み込む -`statSync` | 同期的にファイルのステータスを読み込む -`render` | ファイルをレンダリングする -`renderSync` | 同期的にファイルをレンダリングする +| メソッド | 説明 | +| ------------ | -------------------------------------- | +| `read` | ファイルを読み込む | +| `readSync` | 同期的にファイルを読み込む | +| `stat` | ファイルのステータスを読み込む | +| `statSync` | 同期的にファイルのステータスを読み込む | +| `render` | ファイルをレンダリングする | +| `renderSync` | 同期的にファイルをレンダリングする | [util.Pattern]: https://github.com/hexojs/hexo-util#patternrule diff --git a/source/ja/api/console.md b/source/ja/api/console.md index 26c482bf6c..12104dbd18 100644 --- a/source/ja/api/console.md +++ b/source/ja/api/console.md @@ -1,21 +1,22 @@ --- title: コンソール --- + コンソールはHexoとユーザーとの橋渡しをします。コンソールコマンドの登録方法を説明します。 ## 概要 -``` js -hexo.extend.console.register(name, desc, options, function(args){ +```js +hexo.extend.console.register(name, desc, options, function (args) { // ... }); ``` -引数 | 説明 ---- | --- -`name` | 名前 -`desc` | 説明 -`options`| オプション +| 引数 | 説明 | +| --------- | ---------- | +| `name` | 名前 | +| `desc` | 説明 | +| `options` | オプション | 関数には引数`args`が渡されます。これはユーザーがターミナルに入力する引数です。[Minimist]によって解析されます。 @@ -25,8 +26,10 @@ hexo.extend.console.register(name, desc, options, function(args){ コンソールコマンドの使用方法。例えば: -``` js -{usage: '[layout] <title>'} +```js +{ + usage: "[layout] <title>"; +} // hexo new [layout] <title> ``` @@ -34,12 +37,12 @@ hexo.extend.console.register(name, desc, options, function(args){ コンソールコマンドの各引数の説明。例えば: -``` js +```js { arguments: [ - {name: 'layout', desc: '記事のレイアウト'}, - {name: 'title', desc: '記事のタイトル'} - ] + { name: "layout", desc: "記事のレイアウト" }, + { name: "title", desc: "記事のタイトル" }, + ]; } ``` @@ -47,11 +50,9 @@ hexo.extend.console.register(name, desc, options, function(args){ コンソールコマンドの各オプションの説明。例えば: -``` js +```js { - options: [ - {name: '-r, --replace', desc: '既存のファイルを置き換える'} - ] + options: [{ name: "-r, --replace", desc: "既存のファイルを置き換える" }]; } ``` @@ -61,8 +62,8 @@ hexo.extend.console.register(name, desc, options, function(args){ ## 例 -``` js -hexo.extend.console.register('config', '設定を表示する', function(args){ +```js +hexo.extend.console.register("config", "設定を表示する", function (args) { console.log(hexo.config); }); ``` diff --git a/source/ja/api/deployer.md b/source/ja/api/deployer.md index e8a06e63e6..f082930677 100644 --- a/source/ja/api/deployer.md +++ b/source/ja/api/deployer.md @@ -1,12 +1,13 @@ --- title: デプロイヤー --- + デプロイヤーは、複雑なコマンドなしにウェブサイトをサーバーに素早くデプロイします。 ## 概要 -``` js -hexo.extend.deployer.register(name, function(args){ +```js +hexo.extend.deployer.register(name, function (args) { // ... }); ``` diff --git a/source/ja/api/events.md b/source/ja/api/events.md index 5c4a294046..75d2af0b1a 100644 --- a/source/ja/api/events.md +++ b/source/ja/api/events.md @@ -1,6 +1,7 @@ --- title: イベント --- + Hexoは[EventEmitter]を継承しています。Hexoからのイベントの発火を監視するには`on`メソッドを、イベントを発火させるには`emit`メソッドを使用します。詳細については、Node.jsのAPIドキュメントを参照してください。 ### deployBefore @@ -27,16 +28,16 @@ Hexoが終了する前に発火します。 新しい記事が作成された後に発火します。このイベントには、記事データが返されます: -``` js -hexo.on('new', function(post){ +```js +hexo.on("new", function (post) { // }); ``` -データ | 説明 ---- | --- -`post.path` | 記事ファイルの完全なパス -`post.content` | 記事ファイルの内容 +| データ | 説明 | +| -------------- | ------------------------ | +| `post.path` | 記事ファイルの完全なパス | +| `post.content` | 記事ファイルの内容 | ### processBefore diff --git a/source/ja/api/filter.md b/source/ja/api/filter.md index 08a42f6a6e..b3ffe7027c 100644 --- a/source/ja/api/filter.md +++ b/source/ja/api/filter.md @@ -1,11 +1,12 @@ --- title: フィルター --- + フィルターは特定のデータを変更します。Hexoはデータをフィルターに順番に渡し、フィルターがデータを1つずつ変更します。このコンセプトは[WordPress](http://codex.wordpress.org/Plugin_API#Filters)に基づいています。 ## 概要 -``` js +```js hexo.extend.filter.register(type, function() { // User configuration const { config } = this; @@ -22,69 +23,69 @@ hexo.extend.filter.register(type, function() { ## フィルターの実行 -``` js +```js hexo.extend.filter.exec(type, data, options); hexo.extend.filter.execSync(type, data, options); ``` -オプション | 説明 ---- | --- -`context` | コンテキスト -`args` | 引数。配列でなければなりません。 +| オプション | 説明 | +| ---------- | -------------------------------- | +| `context` | コンテキスト | +| `args` | 引数。配列でなければなりません。 | 各フィルターに渡される最初の引数は`data`です。新たな値を返却することで、次のフィルターに渡される`data`を変更できます。何も返却しない場合データは変更されません。`args`を使用してフィルターに他の引数を指定することもできます。例えば: -``` js -hexo.extend.filter.register('test', function(data, arg1, arg2){ +```js +hexo.extend.filter.register("test", function (data, arg1, arg2) { // data === 'some data' // arg1 === 'foo' // arg2 === 'bar' - return 'something'; + return "something"; }); -hexo.extend.filter.register('test', function(data, arg1, arg2){ +hexo.extend.filter.register("test", function (data, arg1, arg2) { // data === 'something' }); -hexo.extend.filter.exec('test', 'some data', { - args: ['foo', 'bar'] +hexo.extend.filter.exec("test", "some data", { + args: ["foo", "bar"], }); ``` フィルターを実行するために以下の方法も使用できます: -``` js +```js hexo.execFilter(type, data, options); hexo.execFilterSync(type, data, options); ``` ## フィルターの登録解除 -``` js +```js hexo.extend.filter.unregister(type, filter); ``` **例** -``` js +```js // 名前付き関数で登録されたフィルターを登録解除 const filterFn = (data) => { - data = 'something'; + data = "something"; return data; }; -hexo.extend.filter.register('example', filterFn); +hexo.extend.filter.register("example", filterFn); -hexo.extend.filter.unregister('example', filterFn); +hexo.extend.filter.unregister("example", filterFn); ``` -``` js +```js // commonjsモジュールで登録されたフィルターを登録解除 -hexo.extend.filter.register('example', require('path/to/filter')); +hexo.extend.filter.register("example", require("path/to/filter")); -hexo.extend.filter.unregister('example', require('path/to/filter')); +hexo.extend.filter.unregister("example", require("path/to/filter")); ``` ## フィルターリスト @@ -97,8 +98,8 @@ Hexoで使用されるフィルターの一覧です。 例えば、タイトルを小文字に変換するには: -``` js -hexo.extend.filter.register('before_post_render', function(data){ +```js +hexo.extend.filter.register("before_post_render", function (data) { data.title = data.title.toLowerCase(); return data; }); @@ -110,9 +111,12 @@ hexo.extend.filter.register('before_post_render', function(data){ 例えば、`@username`をTwitterプロファイルへのリンクに置き換えるには: -``` js -hexo.extend.filter.register('after_post_render', function(data){ - data.content = data.content.replace(/@(\d+)/, '<a href="http://twitter.com/$1">#$1</a>'); +```js +hexo.extend.filter.register("after_post_render", function (data) { + data.content = data.content.replace( + /@(\d+)/, + '<a href="http://twitter.com/$1">#$1</a>', + ); return data; }); ``` @@ -121,8 +125,8 @@ hexo.extend.filter.register('after_post_render', function(data){ Hexoが終了する直前、つまり`hexo.exit`が呼び出された直後に実行されます。 -``` js -hexo.extend.filter.register('before_exit', function(){ +```js +hexo.extend.filter.register("before_exit", function () { // ... }); ``` @@ -131,8 +135,8 @@ hexo.extend.filter.register('before_exit', function(){ 生成が開始される直前に実行されます。 -``` js -hexo.extend.filter.register('before_generate', function(){ +```js +hexo.extend.filter.register("before_generate", function () { // ... }); ``` @@ -141,8 +145,8 @@ hexo.extend.filter.register('before_generate', function(){ 生成が終了した直後に実行されます。 -``` js -hexo.extend.filter.register('after_generate', function(){ +```js +hexo.extend.filter.register("after_generate", function () { // ... }); ``` @@ -153,8 +157,8 @@ hexo.extend.filter.register('after_generate', function(){ 例えば、テンプレートのローカル変数に現在の時間を追加するには: -``` js -hexo.extend.filter.register('template_locals', function(locals){ +```js +hexo.extend.filter.register("template_locals", function (locals) { locals.now = Date.now(); return locals; }); @@ -164,8 +168,8 @@ hexo.extend.filter.register('template_locals', function(locals){ Hexoが初期化、つまり`hexo.init`が完了した直後に実行されます。 -``` js -hexo.extend.filter.register('after_init', function(){ +```js +hexo.extend.filter.register("after_init", function () { // ... }); ``` @@ -174,8 +178,8 @@ hexo.extend.filter.register('after_init', function(){ 新しい記事を作成する際のパスを決定するために実行されます。 -``` js -hexo.extend.filter.register('new_post_path', function(data, replace){ +```js +hexo.extend.filter.register("new_post_path", function (data, replace) { // ... }); ``` @@ -184,8 +188,8 @@ hexo.extend.filter.register('new_post_path', function(data, replace){ 記事のパーマリンクを決定するために使用されます。 -``` js -hexo.extend.filter.register('post_permalink', function(data){ +```js +hexo.extend.filter.register("post_permalink", function (data) { // ... }); ``` @@ -198,8 +202,8 @@ hexo.extend.filter.register('post_permalink', function(data){ `hexo clean`コマンドで生成されたファイルとキャッシュが削除された後に実行されます。 -``` js -hexo.extend.filter.register('after_clean', function(){ +```js +hexo.extend.filter.register("after_clean", function () { // 他の一時ファイルを削除する }); ``` @@ -210,10 +214,10 @@ hexo.extend.filter.register('after_clean', function(){ 例えば、レスポンスヘッダーに`X-Powered-By: Hexo`を追加するには: -``` js -hexo.extend.filter.register('server_middleware', function(app){ - app.use(function(req, res, next){ - res.setHeader('X-Powered-By', 'Hexo'); +```js +hexo.extend.filter.register("server_middleware", function (app) { + app.use(function (req, res, next) { + res.setHeader("X-Powered-By", "Hexo"); next(); }); }); diff --git a/source/ja/api/generator.md b/source/ja/api/generator.md index c3babdd37b..125f6b251c 100644 --- a/source/ja/api/generator.md +++ b/source/ja/api/generator.md @@ -1,12 +1,13 @@ --- title: ジェネレータ --- + ジェネレータは、処理されたファイルに基づいてルートを構築します。 ## 概要 -``` js -hexo.extend.generator.register(name, function(locals){ +```js +hexo.extend.generator.register(name, function (locals) { // ... }); ``` @@ -15,27 +16,27 @@ hexo.extend.generator.register(name, function(locals){ ## ルートの更新 -``` js -hexo.extend.generator.register('test', function(locals){ +```js +hexo.extend.generator.register("test", function (locals) { // オブジェクト return { - path: 'foo', - data: 'foo' + path: "foo", + data: "foo", }; // 配列 return [ - {path: 'foo', data: 'foo'}, - {path: 'bar', data: 'bar'} + { path: "foo", data: "foo" }, + { path: "bar", data: "bar" }, ]; }); ``` -属性 | 説明 ---- | --- -`path` | 先頭の`/`を含まないパス。 -`data` | データ -`layout` | レイアウト。レンダリングに使用するレイアウトを文字列または配列で指定します。無指定の場合、ルートは`data`を直接返します。 +| 属性 | 説明 | +| -------- | ------------------------------------------------------------------------------------------------------------------------ | +| `path` | 先頭の`/`を含まないパス。 | +| `data` | データ | +| `layout` | レイアウト。レンダリングに使用するレイアウトを文字列または配列で指定します。無指定の場合、ルートは`data`を直接返します。 | ソースファイルが更新されると、Hexoはすべてのジェネレータを実行し、ルートを再構築します。**ここではあくまでデータを返し、直接ルーターにアクセスしないでください。** @@ -48,12 +49,12 @@ hexo.extend.generator.register('test', function(locals){ 次に、`layout`属性を設定してテーマテンプレートでレンダリングします。この例では2つのレイアウトを設定しています。`archive`レイアウトが存在しない場合は、代わりに`index`レイアウトが使用されます。 ```js -hexo.extend.generator.register('archive', function(locals){ +hexo.extend.generator.register("archive", function (locals) { return { - path: 'archives/index.html', + path: "archives/index.html", data: locals, - layout: ['archive', 'index'] - } + layout: ["archive", "index"], + }; }); ``` @@ -61,15 +62,15 @@ hexo.extend.generator.register('archive', function(locals){ 公式ツール[hexo-pagination]を使用して、ページネーション付きのアーカイブページを簡単に構築できます。 -``` js -var pagination = require('hexo-pagination'); +```js +var pagination = require("hexo-pagination"); -hexo.extend.generator.register('archive', function(locals){ +hexo.extend.generator.register("archive", function (locals) { // hexo-paginationは/archivesルートにindex.htmlを作成します - return pagination('archives', locals.posts, { + return pagination("archives", locals.posts, { perPage: 10, - layout: ['archive', 'index'], - data: {} + layout: ["archive", "index"], + data: {}, }); }); ``` @@ -78,13 +79,13 @@ hexo.extend.generator.register('archive', function(locals){ `locals.posts`内のすべての記事を走査し、すべての記事のルートを作成します。 -``` js -hexo.extend.generator.register('post', function(locals){ - return locals.posts.map(function(post){ +```js +hexo.extend.generator.register("post", function (locals) { + return locals.posts.map(function (post) { return { path: post.path, data: post, - layout: 'post' + layout: "post", }; }); }); @@ -94,15 +95,15 @@ hexo.extend.generator.register('post', function(locals){ この例ではデータを明示的に返さず、ルートが必要なときにのみ`fs.ReadStream`を生成する関数を`data`に設定しています。 -``` js -var fs = require('hexo-fs'); +```js +var fs = require("hexo-fs"); -hexo.extend.generator.register('asset', function(locals){ +hexo.extend.generator.register("asset", function (locals) { return { - path: 'file.txt', - data: function(){ - return fs.createReadStream('path/to/file.txt') - } + path: "file.txt", + data: function () { + return fs.createReadStream("path/to/file.txt"); + }, }; }); ``` diff --git a/source/ja/api/helper.md b/source/ja/api/helper.md index 8ce54b7bd7..2928b52b57 100644 --- a/source/ja/api/helper.md +++ b/source/ja/api/helper.md @@ -1,27 +1,28 @@ --- title: ヘルパー --- + ヘルパーを使用すると、テンプレートにスニペットを簡単に追加できます。より複雑なコードを扱う場合、テンプレートよりもヘルパーを使用することをお勧めします。 ヘルパーは`source`ファイルからアクセスできません。 ## 概要 -``` js -hexo.extend.helper.register(name, function(){ +```js +hexo.extend.helper.register(name, function () { // ... }); ``` ## 例 -``` js -hexo.extend.helper.register('js', function(path){ +```js +hexo.extend.helper.register("js", function (path) { return '<script src="' + path + '"></script>'; }); ``` -``` js +```js <%- js('script.js') %> // <script src="script.js"></script> ``` @@ -36,8 +37,8 @@ hexo.extend.helper.register('js', function(path){ すべてのヘルパーは同じコンテキストで実行されます。例えば、カスタムヘルパー内で[`url_for()`](../docs/helpers#url-for)を使用するには: -``` js -hexo.extend.helper.register('lorem', function(path) { +```js +hexo.extend.helper.register("lorem", function (path) { return '<script src="' + this.url_for(path) + '"></script>'; }); ``` @@ -46,6 +47,6 @@ hexo.extend.helper.register('lorem', function(path) { `hexo.extend.helper.get`はヘルパー関数を返しますが、それにはhexoがコンテキストとして必要ですので: -``` js -const url_for = hexo.extend.helper.get('url_for').bind(hexo); +```js +const url_for = hexo.extend.helper.get("url_for").bind(hexo); ``` diff --git a/source/ja/api/index.md b/source/ja/api/index.md index 8b868f9059..2ec29fb3c8 100644 --- a/source/ja/api/index.md +++ b/source/ja/api/index.md @@ -1,6 +1,7 @@ --- title: API --- + このドキュメントではAPIについてより詳細な情報を提供します。Hexoのソースコードを変更したり新しいプラグインを作成する方に特に役立ちます。Hexoの基本的な使用法に興味がある場合は、代わりに[ドキュメント](../docs)を参照してください。 このドキュメントはHexo 3以降にのみ有効です。 @@ -9,22 +10,22 @@ title: API まず、Hexoインスタンスを作成する必要があります。新しいインスタンスは2つの引数を取ります: ウェブサイトのルートディレクトリ`base_dir`と、初期化オプションを含むオブジェクトです。次に、このインスタンスの`init`メソッドを呼び出して初期化します。これによりHexoは設定とプラグインを読み込みます。 -``` js -var Hexo = require('hexo'); +```js +var Hexo = require("hexo"); var hexo = new Hexo(process.cwd(), {}); -hexo.init().then(function(){ +hexo.init().then(function () { // ... }); ``` -オプション | 説明 | デフォルト ---- | --- | --- -`debug` | デバッグモードを有効にします。端末にデバッグメッセージを表示し、ルートディレクトリに`debug.log`を保存します。 | `false` -`safe` | セーフモードを有効にします。プラグインを読み込みません。 | `false` -`silent` | サイレントモードを有効にします。端末にメッセージを表示しません。 | `false` -`config` | 設定ファイルのパスを指定します。 | `_config.yml` -`draft` / `drafts`| 下書きを記事リストに追加します。<br> 例: `hexo.locals.get('posts')`を使用するとき | _config.ymlの`render_drafts` +| オプション | 説明 | デフォルト | +| ------------------ | ------------------------------------------------------------------------------------------------------------- | ----------------------------- | +| `debug` | デバッグモードを有効にします。端末にデバッグメッセージを表示し、ルートディレクトリに`debug.log`を保存します。 | `false` | +| `safe` | セーフモードを有効にします。プラグインを読み込みません。 | `false` | +| `silent` | サイレントモードを有効にします。端末にメッセージを表示しません。 | `false` | +| `config` | 設定ファイルのパスを指定します。 | `_config.yml` | +| `draft` / `drafts` | 下書きを記事リストに追加します。<br> 例: `hexo.locals.get('posts')`を使用するとき | \_config.ymlの`render_drafts` | ## ファイルの読み込み @@ -32,12 +33,12 @@ Hexoはファイルを読み込むために`load`と`watch`の2つのメソッ 両方のメソッドはファイルリストを読み込み、それらを対応するプロセッサに渡します。全てのファイルが処理された後、ジェネレーターを呼び出してルートを作成します。 -``` js -hexo.load().then(function(){ +```js +hexo.load().then(function () { // ... }); -hexo.watch().then(function(){ +hexo.watch().then(function () { // 後で hexo.unwatch() を呼び出して監視を停止できます。 }); ``` @@ -46,26 +47,29 @@ hexo.watch().then(function(){ Hexoインスタンスの`call`メソッドを使用することで、任意のコンソールコマンドを明示的に呼び出すことができます。この呼び出しには2つの引数があります。コンソールコマンドの名前と、オプション引数です。異なるコンソールコマンドには異なるオプションが利用可能です。 -``` js -hexo.call('generate', {}).then(function(){ +```js +hexo.call("generate", {}).then(function () { // ... }); ``` -``` js -hexo.call('list', { _: ['post'] }).then(function() { +```js +hexo.call("list", { _: ["post"] }).then(function () { // ... -}) +}); ``` ## 終了 コンソールコマンドの成功または失敗の完了時には、`exit`メソッドを呼び出すべきです。これによりHexoは正常に終了し、データベースの保存など重要な処理を終えることができます。 -``` js -hexo.call('generate').then(function(){ - return hexo.exit(); -}).catch(function(err){ - return hexo.exit(err); -}); +```js +hexo + .call("generate") + .then(function () { + return hexo.exit(); + }) + .catch(function (err) { + return hexo.exit(err); + }); ``` diff --git a/source/ja/api/injector.md b/source/ja/api/injector.md index d26be48ed2..1af7359ec4 100644 --- a/source/ja/api/injector.md +++ b/source/ja/api/injector.md @@ -7,7 +7,7 @@ title: インジェクター ## 概要 ```js -hexo.extend.injector.register(entry, value, to) +hexo.extend.injector.register(entry, value, to); ``` ### entry `<string>` @@ -40,24 +40,34 @@ HTML内でコードが挿入される場所です。 - `tag`: タグページのみに挿入します(`is_tag()`ヘルパーが`true`の場合)。 - カスタムレイアウト名も使用可能です。詳細は[執筆 - レイアウト](../docs/writing#レイアウト)を参照してください。 ----- +--- 他にも内部関数があります。詳細は、[hexojs/hexo#4049](https://github.com/hexojs/hexo/pull/4049) を参照してください。 ## 例 ```js -const css = hexo.extend.helper.get('css').bind(hexo); -const js = hexo.extend.helper.get('js').bind(hexo); - -hexo.extend.injector.register('head_end', () => { - return css('https://cdn.jsdelivr.net/npm/aplayer@1.10.1/dist/APlayer.min.css'); -}, 'music'); - -hexo.extend.injector.register('body_end', '<script src="https://cdn.jsdelivr.net/npm/aplayer@1.10.1/dist/APlayer.min.js">', 'music'); - -hexo.extend.injector.register('body_end', () => { - return js('/js/jquery.js'); +const css = hexo.extend.helper.get("css").bind(hexo); +const js = hexo.extend.helper.get("js").bind(hexo); + +hexo.extend.injector.register( + "head_end", + () => { + return css( + "https://cdn.jsdelivr.net/npm/aplayer@1.10.1/dist/APlayer.min.css", + ); + }, + "music", +); + +hexo.extend.injector.register( + "body_end", + '<script src="https://cdn.jsdelivr.net/npm/aplayer@1.10.1/dist/APlayer.min.js">', + "music", +); + +hexo.extend.injector.register("body_end", () => { + return js("/js/jquery.js"); }); ``` @@ -69,10 +79,10 @@ hexo.extend.injector.register('body_end', () => { 1. -``` js -const css = hexo.extend.helper.get('css').bind(hexo); +```js +const css = hexo.extend.helper.get("css").bind(hexo); -hexo.extend.injector.register('head_end', () => { +hexo.extend.injector.register("head_end", () => { const { cssPath } = hexo.config.fooPlugin; return css(cssPath); }); @@ -80,23 +90,23 @@ hexo.extend.injector.register('head_end', () => { 2. -``` js index.js +```js index.js /* global hexo */ -hexo.extend.injector.register('head_end', require('./lib/inject').bind(hexo)) +hexo.extend.injector.register("head_end", require("./lib/inject").bind(hexo)); ``` -``` js lib/inject.js +```js lib/inject.js module.exports = function () { - const css = this.extend.helper.get('css'); + const css = this.extend.helper.get("css"); const { cssPath } = this.config.fooPlugin; return css(cssPath); -} +}; ``` -``` js lib/inject.js +```js lib/inject.js function injectFn() { - const css = this.extend.helper.get('css'); + const css = this.extend.helper.get("css"); const { cssPath } = this.config.fooPlugin; return css(cssPath); } @@ -106,23 +116,23 @@ module.exports = injectFn; 3. -``` js index.js +```js index.js /* global hexo */ -hexo.extend.injector.register('head_end', require('./lib/inject')(hexo)) +hexo.extend.injector.register("head_end", require("./lib/inject")(hexo)); ``` -``` js lib/inject.js +```js lib/inject.js module.exports = (hexo) => () => { - const css = hexo.extend.helper.get('css').bind(hexo); + const css = hexo.extend.helper.get("css").bind(hexo); const { cssPath } = hexo.config.fooPlugin; return css(cssPath); }; ``` -``` js lib/inject.js +```js lib/inject.js const injectFn = (hexo) => { - const css = hexo.extend.helper.get('css').bind(hexo); + const css = hexo.extend.helper.get("css").bind(hexo); const { cssPath } = hexo.config.fooPlugin; return css(cssPath); }; diff --git a/source/ja/api/locals.md b/source/ja/api/locals.md index e29c3177ff..d36b8b0d68 100644 --- a/source/ja/api/locals.md +++ b/source/ja/api/locals.md @@ -1,26 +1,27 @@ --- title: ローカル変数 --- + ローカル変数はテンプレート内の`site`変数としてレンダリング時に利用されます。 ## デフォルト変数 -変数 | 説明 ---- | --- -`posts` | すべての記事 -`pages` | すべてのページ -`categories` | すべてのカテゴリー -`tags` | すべてのタグ +| 変数 | 説明 | +| ------------ | ------------------ | +| `posts` | すべての記事 | +| `pages` | すべてのページ | +| `categories` | すべてのカテゴリー | +| `tags` | すべてのタグ | ## 変数の取得 -``` js -hexo.locals.get('posts') +```js +hexo.locals.get("posts"); ``` ## 変数の設定 -``` js +```js hexo.locals.set('posts', function(){ return ... }); @@ -28,18 +29,18 @@ hexo.locals.set('posts', function(){ ## 変数の削除 -``` js -hexo.locals.remove('posts'); +```js +hexo.locals.remove("posts"); ``` ## すべての変数を取得 -``` js +```js hexo.locals.toObject(); ``` ## キャッシュの無効化 -``` js +```js hexo.locals.invalidate(); ``` diff --git a/source/ja/api/migrator.md b/source/ja/api/migrator.md index 9c54b6780f..0e89f7fd8a 100644 --- a/source/ja/api/migrator.md +++ b/source/ja/api/migrator.md @@ -1,12 +1,13 @@ --- title: マイグレーター --- + マイグレーターは、他のシステムからHexoへのウェブサイトの移行を行います。 ## 概要 -``` js -hexo.extend.migrator.register(name, function(args){ +```js +hexo.extend.migrator.register(name, function (args) { // ... }); ``` diff --git a/source/ja/api/posts.md b/source/ja/api/posts.md index 60390e031e..b6f29514fd 100644 --- a/source/ja/api/posts.md +++ b/source/ja/api/posts.md @@ -1,55 +1,56 @@ --- title: 記事 --- + ## 記事の作成 -``` js +```js hexo.post.create(data, replace); ``` -引数 | 説明 ---- | --- -`data` | データ -`replace` | 既存のファイルを置き換えるか +| 引数 | 説明 | +| --------- | ---------------------------- | +| `data` | データ | +| `replace` | 既存のファイルを置き換えるか | 記事の属性は`data`に定義されていますが、以下の表は全てを網羅していないかもしれません。追加の属性がFront Matterに存在する場合もあります。 -データ | 説明 ---- | --- -`title` | タイトル -`slug` | URL -`layout` | レイアウト。`default_layout`設定がデフォルトです。 -`path` | パス。デフォルトでは`new_post_path`設定に基づいて記事のパスをHexoが構築します。 -`date` | 日付。デフォルトでは現在の日付です。 +| データ | 説明 | +| -------- | ------------------------------------------------------------------------------- | +| `title` | タイトル | +| `slug` | URL | +| `layout` | レイアウト。`default_layout`設定がデフォルトです。 | +| `path` | パス。デフォルトでは`new_post_path`設定に基づいて記事のパスをHexoが構築します。 | +| `date` | 日付。デフォルトでは現在の日付です。 | ## 下書きの公開 -``` js +```js hexo.post.publish(data, replace); ``` -引数 | 説明 ---- | --- -`data` | データ -`replace` | 既存のファイルを置き換えるか +| 引数 | 説明 | +| --------- | ---------------------------- | +| `data` | データ | +| `replace` | 既存のファイルを置き換えるか | 記事の属性は`data`に定義されていますが、以下の表は全てを網羅していないかもしれません。追加の属性がFront Matterに存在する場合もあります。 -データ | 説明 ---- | --- -`slug` | ファイル名(必須) -`layout` | レイアウト。`default_layout`設定がデフォルトです。 +| データ | 説明 | +| -------- | -------------------------------------------------- | +| `slug` | ファイル名(必須) | +| `layout` | レイアウト。`default_layout`設定がデフォルトです。 | ## レンダリング -``` js +```js hexo.post.render(source, data); ``` -引数 | 説明 ---- | --- -`source` | ファイルの完全なパス(任意) -`data` | データ +| 引数 | 説明 | +| -------- | ---------------------------- | +| `source` | ファイルの完全なパス(任意) | +| `data` | データ | データには`content`属性が含まれている必要があります。そうでない場合、Hexoは元のファイルを読み込もうとします。この関数の実行順序は以下の通りです: @@ -59,4 +60,3 @@ hexo.post.render(source, data); - `after_post_render`フィルターを実行 [Nunjucks]: https://mozilla.github.io/nunjucks/ - diff --git a/source/ja/api/processor.md b/source/ja/api/processor.md index 6d5d1d3d37..3c00e9a4ff 100644 --- a/source/ja/api/processor.md +++ b/source/ja/api/processor.md @@ -1,13 +1,14 @@ --- title: プロセッサー --- + プロセッサーは、`source`フォルダ内のソースファイルの処理を行います。 ## 概要 -``` js -hexo.extend.processor.register(rule, function(file){ - // ... +```js +hexo.extend.processor.register(rule, function (file) { + // ... }); ``` diff --git a/source/ja/api/renderer.md b/source/ja/api/renderer.md index 814840c2bb..d8ea781981 100644 --- a/source/ja/api/renderer.md +++ b/source/ja/api/renderer.md @@ -1,71 +1,86 @@ --- title: レンダラー --- + レンダラーは、コンテンツをレンダリングします。 ## 概要 -``` js -hexo.extend.renderer.register(name, output, function(data, options){ - // ... -}, sync); +```js +hexo.extend.renderer.register( + name, + output, + function (data, options) { + // ... + }, + sync, +); ``` -引数 | 説明 ---- | --- -`name` | 入力ファイルの拡張子(小文字、先頭の`.`なし) -`output` | 出力ファイルの拡張子(小文字、先頭の`.`なし) -`sync` | 同期モード +| 引数 | 説明 | +| -------- | --------------------------------------------- | +| `name` | 入力ファイルの拡張子(小文字、先頭の`.`なし) | +| `output` | 出力ファイルの拡張子(小文字、先頭の`.`なし) | +| `sync` | 同期モード | レンダリング関数には3つの引数が渡されます: -引数 | 説明 ---- | --- -`data` | ファイルパス`path`とファイルコンテンツ`text`の2つの属性を含みます。`path`は必ず存在するとは限りません。 -`option` | オプション -`callback` | `err`, `value`の2つのパラメータを持つコールバック関数。 +| 引数 | 説明 | +| ---------- | ------------------------------------------------------------------------------------------------------- | +| `data` | ファイルパス`path`とファイルコンテンツ`text`の2つの属性を含みます。`path`は必ず存在するとは限りません。 | +| `option` | オプション | +| `callback` | `err`, `value`の2つのパラメータを持つコールバック関数。 | ## 例 ### 非同期モード -``` js -var stylus = require('stylus'); +```js +var stylus = require("stylus"); // Callback -hexo.extend.renderer.register('styl', 'css', function(data, options, callback){ - stylus(data.text).set('filename', data.path).render(callback); -}); +hexo.extend.renderer.register( + "styl", + "css", + function (data, options, callback) { + stylus(data.text).set("filename", data.path).render(callback); + }, +); // Promise -hexo.extend.renderer.register('styl', 'css', function(data, options){ - return new Promise(function(resolve, reject){ - resolve('test'); +hexo.extend.renderer.register("styl", "css", function (data, options) { + return new Promise(function (resolve, reject) { + resolve("test"); }); }); ``` ### 同期モード -``` js -var ejs = require('ejs'); - -hexo.extend.renderer.register('ejs', 'html', function(data, options){ - options.filename = data.path; - return ejs.render(data.text, options); -}, true); +```js +var ejs = require("ejs"); + +hexo.extend.renderer.register( + "ejs", + "html", + function (data, options) { + options.filename = data.path; + return ejs.render(data.text, options); + }, + true, +); ``` ### Nunjucksタグを無効にする Nunjucksタグ`{{ }}`や`{% %}`([タグプラグイン](../docs/tag-plugins)で使用される)はデフォルトで処理されますが、次の方法で無効にできます: -``` js +```js function lessFn(data, options) { // do something } -lessFn.disableNunjucks = true +lessFn.disableNunjucks = true; -hexo.extend.renderer.register('less', 'css', lessFn); +hexo.extend.renderer.register("less", "css", lessFn); ``` diff --git a/source/ja/api/rendering.md b/source/ja/api/rendering.md index 764d66eb0e..05de79f4d8 100644 --- a/source/ja/api/rendering.md +++ b/source/ja/api/rendering.md @@ -1,14 +1,15 @@ --- title: レンダリング --- + Hexoにはファイルや文字列をレンダリングするための2つの方法があります。非同期の`hexo.render.render`メソッドと同期の`hexo.render.renderSync`メソッドです。これら2つの方法は非常に似ているため、以下では非同期の`hexo.render.render`についてのみ詳しく説明します。 ## 文字列のレンダリング 文字列をレンダリングする際、Hexoがどのレンダリングエンジンを使用すべきか知るために`engine`を指定する必要があります。 -``` js -hexo.render.render({text: 'example', engine: 'swig'}).then(function(result){ +```js +hexo.render.render({ text: "example", engine: "swig" }).then(function (result) { // ... }); ``` @@ -17,8 +18,8 @@ hexo.render.render({text: 'example', engine: 'swig'}).then(function(result){ ファイルをレンダリングする際は、Hexoがファイルの拡張子に基づいて自動的に関連するレンダリングエンジンを検出するため、`engine`を指定する必要はありません。もちろん、`engine`を明示的に定義することもできます。 -``` js -hexo.render.render({path: 'path/to/file.swig'}).then(function(result){ +```js +hexo.render.render({ path: "path/to/file.swig" }).then(function (result) { // ... }); ``` @@ -27,8 +28,8 @@ hexo.render.render({path: 'path/to/file.swig'}).then(function(result){ 第二引数としてオプションオブジェクトを渡すことができます。 -``` js -hexo.render.render({text: ''}, {foo: 'foo'}).then(function(result){ +```js +hexo.render.render({ text: "" }, { foo: "foo" }).then(function (result) { // ... }); ``` @@ -37,10 +38,10 @@ hexo.render.render({text: ''}, {foo: 'foo'}).then(function(result){ レンダリングが完了すると、Hexoは対応する`after_render`フィルターを実行します。例えば、この機能を使用してJavaScriptのミニファイを実装できます。 -``` js -var UglifyJS = require('uglify-js'); +```js +var UglifyJS = require("uglify-js"); -hexo.extend.filter.register('after_render:js', function(str, data){ +hexo.extend.filter.register("after_render:js", function (str, data) { var result = UglifyJS.minify(str); return result.code; }); @@ -50,30 +51,30 @@ hexo.extend.filter.register('after_render:js', function(str, data){ `isRenderable`または`isRenderableSync`メソッドを使用して、ファイルパスがレンダリング可能かチェックできます。対応するレンダラーが登録されている場合のみ、このメソッドはtrueを返します。 -``` js -hexo.render.isRenderable('layout.swig') // true -hexo.render.isRenderable('image.png') // false +```js +hexo.render.isRenderable("layout.swig"); // true +hexo.render.isRenderable("image.png"); // false ``` ## 出力拡張子を取得 レンダリングされた出力の拡張子を取得するには、`getOutput`メソッドを使用します。ファイルがレンダリング可能でない場合、このメソッドは空の文字列を返します。 -``` js -hexo.render.getOutput('layout.swig') // html -hexo.render.getOutput('image.png') // '' +```js +hexo.render.getOutput("layout.swig"); // html +hexo.render.getOutput("image.png"); // '' ``` ## Nunjucksタグを無効にする [タグプラグイン](../docs/tag-plugins)を使用していない場合で、コンテンツの[エスケープ](../docs/troubleshooting#コンテンツのエスケープ)を使用せずに記事内で`{{ }}`または`{% %}`を使用したい場合は、既存のレンダラーでNunjucksタグの処理を無効にすることができます: -``` js +```js // 以下の例は'.md'ファイル拡張子にのみ適用されます // 他の拡張子も指定する必要があるかもしれません。例: '.markdown', '.mkd' -const renderer = hexo.render.renderer.get('md') +const renderer = hexo.render.renderer.get("md"); if (renderer) { - renderer.disableNunjucks = true - hexo.extend.renderer.register('md', 'html', renderer) + renderer.disableNunjucks = true; + hexo.extend.renderer.register("md", "html", renderer); } ``` diff --git a/source/ja/api/router.md b/source/ja/api/router.md index d7dd9443cc..f6320ac1f1 100644 --- a/source/ja/api/router.md +++ b/source/ja/api/router.md @@ -1,15 +1,16 @@ --- title: ルーター --- + ルーターはサイトで使用されるすべてのパスを保存します。 ## パスの取得 `get`メソッドは[Stream]を返却します。たとえば、指定された宛先にパスデータを保存するには: -``` js -var data = hexo.route.get('index.html'); -var dest = fs.createWriteStream('somewhere'); +```js +var data = hexo.route.get("index.html"); +var dest = fs.createWriteStream("somewhere"); data.pipe(dest); ``` @@ -18,32 +19,32 @@ data.pipe(dest); `set`メソッドは文字列、[Buffer]、または関数を引数に取ります。 -``` js +```js // 文字列 -hexo.route.set('index.html', 'index') +hexo.route.set("index.html", "index"); // Buffer -hexo.route.set('index.html', new Buffer('index')); +hexo.route.set("index.html", new Buffer("index")); // 関数 (Promise) -hexo.route.set('index.html', function(){ - return new Promise(function(resolve, reject){ - resolve('index'); +hexo.route.set("index.html", function () { + return new Promise(function (resolve, reject) { + resolve("index"); }); }); // 関数 (コールバック) -hexo.route.set('index.html', function(callback){ - callback(null, 'index'); +hexo.route.set("index.html", function (callback) { + callback(null, "index"); }); ``` パスが変更されたかどうかのブール値も設定できます。これにより、変更されていないファイルを無視することでファイル生成を高速化できます。 -``` js -hexo.route.set('index.html', { - data: 'index', - modified: false +```js +hexo.route.set("index.html", { + data: "index", + modified: false, }); // hexo.route.isModified('index.html') => false @@ -51,13 +52,13 @@ hexo.route.set('index.html', { ## パスの削除 -``` js -hexo.route.remove('index.html'); +```js +hexo.route.remove("index.html"); ``` ## ルートのリストを取得 -``` js +```js hexo.route.list(); ``` @@ -65,8 +66,8 @@ hexo.route.list(); `format`メソッドは文字列を有効なパスに変換します。 -``` js -hexo.route.format('archives/'); +```js +hexo.route.format("archives/"); // archives/index.html ``` diff --git a/source/ja/api/scaffolds.md b/source/ja/api/scaffolds.md index 2b64e13273..e93a6d2303 100644 --- a/source/ja/api/scaffolds.md +++ b/source/ja/api/scaffolds.md @@ -1,20 +1,21 @@ --- title: スキャフォールド --- + ## スキャフォールドの取得 -``` js +```js hexo.scaffold.get(name); ``` ## スキャフォールドの設定 -``` js +```js hexo.scaffold.set(name, content); ``` ## スキャフォールドの削除 -``` js +```js hexo.scaffold.remove(name); ``` diff --git a/source/ja/api/tag.md b/source/ja/api/tag.md index a2f99f24ce..8368477111 100644 --- a/source/ja/api/tag.md +++ b/source/ja/api/tag.md @@ -1,14 +1,19 @@ --- title: タグ --- + タグを使用することで、記事に簡単にスニペットを挿入できます。 ## 概要 -``` js -hexo.extend.tag.register(name, function(args, content){ - // ... -}, options); +```js +hexo.extend.tag.register( + name, + function (args, content) { + // ... + }, + options, +); ``` タグ関数には`args`と`content`の2つの引数が渡されます。`args`はタグに渡された引数、`content`はタグでラップされたコンテンツです。 @@ -19,22 +24,22 @@ Hexo 3での非同期レンダリングの導入以来、レンダリングに `unregister()`を使用して、既存の[タグプラグイン](../docs/tag-plugins)をカスタム関数で置き換えます。 -``` js +```js hexo.extend.tag.unregister(name); ``` **例** -``` js +```js const tagFn = (args, content) => { - content = 'something'; + content = "something"; return content; }; // https://hexo.io/docs/tag-plugins#YouTube -hexo.extend.tag.unregister('youtube'); +hexo.extend.tag.unregister("youtube"); -hexo.extend.tag.register('youtube', tagFn); +hexo.extend.tag.register("youtube", tagFn); ``` ## オプション @@ -53,10 +58,14 @@ hexo.extend.tag.register('youtube', tagFn); Youtubeビデオを挿入します。 -``` js -hexo.extend.tag.register('youtube', function(args){ +```js +hexo.extend.tag.register("youtube", function (args) { var id = args[0]; - return '<div class="video-container"><iframe width="560" height="315" src="http://www.youtube.com/embed/' + id + '" frameborder="0" allowfullscreen></iframe></div>'; + return ( + '<div class="video-container"><iframe width="560" height="315" src="http://www.youtube.com/embed/' + + id + + '" frameborder="0" allowfullscreen></iframe></div>' + ); }); ``` @@ -64,29 +73,43 @@ hexo.extend.tag.register('youtube', function(args){ プルクオートを挿入します。 -``` js -hexo.extend.tag.register('pullquote', function(args, content){ - var className = args.join(' '); - return '<blockquote class="pullquote' + className + '">' + content + '</blockquote>'; -}, {ends: true}); +```js +hexo.extend.tag.register( + "pullquote", + function (args, content) { + var className = args.join(" "); + return ( + '<blockquote class="pullquote' + + className + + '">' + + content + + "</blockquote>" + ); + }, + { ends: true }, +); ``` ### 非同期レンダリング ファイルを挿入します。 -``` js -var fs = require('hexo-fs'); -var pathFn = require('path'); - -hexo.extend.tag.register('include_code', function(args){ - var filename = args[0]; - var path = pathFn.join(hexo.source_dir, filename); - - return fs.readFile(path).then(function(content){ - return '<pre><code>' + content + '</code></pre>'; - }); -}, {async: true}); +```js +var fs = require("hexo-fs"); +var pathFn = require("path"); + +hexo.extend.tag.register( + "include_code", + function (args) { + var filename = args[0]; + var path = pathFn.join(hexo.source_dir, filename); + + return fs.readFile(path).then(function (content) { + return "<pre><code>" + content + "</code></pre>"; + }); + }, + { async: true }, +); ``` ## Front Matterとユーザー設定 @@ -95,7 +118,7 @@ hexo.extend.tag.register('include_code', function(args){ 1. -``` js +```js hexo.extend.tag.register('foo', function (args) { const [firstArg] = args; @@ -120,11 +143,11 @@ hexo.extend.tag.register('foo', function (args) { 2. -``` js index.js -hexo.extend.tag.register('foo', require('./lib/foo')(hexo)); +```js index.js +hexo.extend.tag.register("foo", require("./lib/foo")(hexo)); ``` -``` js lib/foo.js +```js lib/foo.js module.exports = hexo => { return function fooFn(args) { const [firstArg] = args; diff --git a/source/ja/api/themes.md b/source/ja/api/themes.md index 8383493de3..bd29e85214 100644 --- a/source/ja/api/themes.md +++ b/source/ja/api/themes.md @@ -1,23 +1,24 @@ --- title: テーマ --- + `hexo.theme`は[Box](box.html)を継承し、テンプレートを保存します。 ## ビューの取得 -``` js +```js hexo.theme.getView(path); ``` ## ビューの設定 -``` js +```js hexo.theme.setView(path, data); ``` ## ビューの削除 -``` js +```js hexo.theme.removeView(path); ``` @@ -25,10 +26,10 @@ hexo.theme.removeView(path); ビューには`render`と`renderSync`の2つのメソッドがあります。これら2つのメソッドは、前者は非同期であり後者は同期である以外は同じです。簡略化のため、ここでは`render`についてのみ説明します。 -``` js -var view = hexo.theme.getView('layout.swig'); +```js +var view = hexo.theme.getView("layout.swig"); -view.render({foo: 1, bar: 2}).then(function(result){ +view.render({ foo: 1, bar: 2 }).then(function (result) { // ... }); ``` diff --git a/source/ja/docs/asset-folders.md b/source/ja/docs/asset-folders.md index c3c3e0be70..bd79c05d65 100644 --- a/source/ja/docs/asset-folders.md +++ b/source/ja/docs/asset-folders.md @@ -1,6 +1,7 @@ --- title: アセットフォルダ --- + ## グローバルアセットフォルダ アセットとは、`source`フォルダ内の記事以外のファイルです。例えば、画像、CSS、JavaScriptファイルなどがこれにあたります。Hexoプロジェクトで数枚の画像を使用するだけの場合、`source/images`ディレクトリに保管するのが最も簡単な方法です。それから、`![](/images/image.jpg)`のようにしてアクセスできます。 @@ -9,7 +10,7 @@ title: アセットフォルダ 定期的に画像やその他のアセットを提供する予定のユーザーや、記事ごとにアセットを分けたいと考えるユーザーのために、Hexoはもっと整理された方法でアセットを管理する方法を提供します。これは少し複雑ですが、非常に便利なアセット管理方法で、`_config.yml`の`post_asset_folder`設定をtrueに設定することで有効にできます。 -``` yaml _config.yml +```yaml _config.yml post_asset_folder: true ``` @@ -42,7 +43,7 @@ post_asset_folder: true 有効にするには: -``` yml _config.yml +```yml _config.yml post_asset_folder: true marked: prependRoot: true diff --git a/source/ja/docs/commands.md b/source/ja/docs/commands.md index fba3b5e232..31ab626d65 100644 --- a/source/ja/docs/commands.md +++ b/source/ja/docs/commands.md @@ -4,7 +4,7 @@ title: コマンド ## init -``` bash +```bash $ hexo init [folder] ``` @@ -17,17 +17,17 @@ $ hexo init [folder] ## new -``` bash +```bash $ hexo new [layout] <title> ``` -新しい記事やページを作成します。`layout`が指定されていない場合、Hexoは[_config.yml](configuration.html)の`default_layout`を使用します。下書きを作成するには`draft`レイアウトを使用します。`title`にスペースが含まれる場合は、引用符で囲んでください。 +新しい記事やページを作成します。`layout`が指定されていない場合、Hexoは[\_config.yml](configuration.html)の`default_layout`を使用します。下書きを作成するには`draft`レイアウトを使用します。`title`にスペースが含まれる場合は、引用符で囲んでください。 -オプション | 説明 ---- | --- -`-p`, `--path` | 記事のパスをカスタマイズします。 -`-r`, `--replace` | 既存の記事を置き換えます。 -`-s`, `--slug` | 記事のURL(スラッグ)をカスタマイズします。 +| オプション | 説明 | +| ----------------- | ------------------------------------------- | +| `-p`, `--path` | 記事のパスをカスタマイズします。 | +| `-r`, `--replace` | 既存の記事を置き換えます。 | +| `-s`, `--slug` | 記事のURL(スラッグ)をカスタマイズします。 | デフォルトでは、Hexoはタイトルを使用してファイルのパスを定義します。ページの場合、その名前のディレクトリとその中に`index.md`ファイルを作成します。`--path`オプションを使用してこの挙動をオーバーライドし、ファイルパスを定義できます: @@ -47,23 +47,23 @@ hexo new page --path about/me ## generate -``` bash +```bash $ hexo generate ``` 静的ファイルを生成します。 -オプション | 説明 ---- | --- -`-d`, `--deploy` | 生成が完了した後にデプロイします -`-w`, `--watch` | ファイルの変更を監視します -`-b`, `--bail` | 生成中に取り扱いされない例外がスローされた場合にエラーを発生させます -`-f`, `--force` | 強制的に再生成します -`-c`, `--concurrency` | 並行して生成されるファイルの最大数。デフォルトは無限です +| オプション | 説明 | +| --------------------- | -------------------------------------------------------------------- | +| `-d`, `--deploy` | 生成が完了した後にデプロイします | +| `-w`, `--watch` | ファイルの変更を監視します | +| `-b`, `--bail` | 生成中に取り扱いされない例外がスローされた場合にエラーを発生させます | +| `-f`, `--force` | 強制的に再生成します | +| `-c`, `--concurrency` | 並行して生成されるファイルの最大数。デフォルトは無限です | ## publish -``` bash +```bash $ hexo publish [layout] <filename> ``` @@ -71,45 +71,45 @@ $ hexo publish [layout] <filename> ## server -``` bash +```bash $ hexo server ``` ローカルサーバーを起動します。デフォルトでは`http://localhost:4000/`です。 -オプション | 説明 ---- | --- -`-p`, `--port` | デフォルトポートを上書きします -`-s`, `--static` | 静的ファイルのみを提供します -`-l`, `--log` | ロガーを有効にします。ログ形式を上書きします。 +| オプション | 説明 | +| ---------------- | ---------------------------------------------- | +| `-p`, `--port` | デフォルトポートを上書きします | +| `-s`, `--static` | 静的ファイルのみを提供します | +| `-l`, `--log` | ロガーを有効にします。ログ形式を上書きします。 | ## deploy -``` bash +```bash $ hexo deploy ``` ウェブサイトをデプロイします。 -オプション | 説明 ---- | --- -`-g`, `--generate` | デプロイ前に生成を行います +| オプション | 説明 | +| ------------------ | -------------------------- | +| `-g`, `--generate` | デプロイ前に生成を行います | ## render -``` bash +```bash $ hexo render <file1> [file2] ... ``` ファイルをレンダリングします。 -オプション | 説明 ---- | --- -`-o`, `--output` | 出力先 +| オプション | 説明 | +| ---------------- | ------ | +| `-o`, `--output` | 出力先 | ## migrate -``` bash +```bash $ hexo migrate <type> ``` @@ -117,7 +117,7 @@ $ hexo migrate <type> ## clean -``` bash +```bash $ hexo clean ``` @@ -125,7 +125,7 @@ $ hexo clean ## list -``` bash +```bash $ hexo list <type> ``` @@ -133,7 +133,7 @@ $ hexo list <type> ## version -``` bash +```bash $ hexo version ``` @@ -151,7 +151,7 @@ $ hexo config [key] [value] ### セーフモード -``` bash +```bash $ hexo --safe ``` @@ -159,7 +159,7 @@ $ hexo --safe ### デバッグモード -``` bash +```bash $ hexo --debug ``` @@ -167,7 +167,7 @@ $ hexo --debug ### サイレントモード -``` bash +```bash $ hexo --silent ``` @@ -175,19 +175,19 @@ $ hexo --silent ### 設定ファイルパスのカスタマイズ -``` bash +```bash $ hexo --config custom.yml ``` カスタム設定ファイル(`_config.yml`の代わり)を使用します。JSONまたはYAML設定ファイルのカンマ区切りリスト(スペースなし)も受け入れ、ファイルを単一の`_multiconfig.yml`に結合します。 -``` bash +```bash $ hexo --config custom.yml,custom2.json ``` ### 下書きの表示 -``` bash +```bash $ hexo --draft ``` @@ -195,7 +195,7 @@ $ hexo --draft ### 現在の作業ディレクトリのカスタマイズ -``` bash +```bash $ hexo --cwd /path/to/cwd ``` diff --git a/source/ja/docs/configuration.md b/source/ja/docs/configuration.md index 8f010cea2f..0e69d280b7 100644 --- a/source/ja/docs/configuration.md +++ b/source/ja/docs/configuration.md @@ -1,31 +1,32 @@ --- title: 設定 --- + `_config.yml`または[代替設定ファイル](#代替設定の使用)でサイトの設定を変更できます。 ### サイト -設定 | 説明 ---- | --- -`title` | ウェブサイトのタイトル -`subtitle` | ウェブサイトのサブタイトル -`description` | ウェブサイトの説明 -`keywords` | ウェブサイトのキーワード。複数の値をサポート。 -`author` | あなたの名前 -`language` | ウェブサイトの言語。[2文字のISO-639-1コード](https://ja.wikipedia.org/wiki/ISO_639-1%E3%82%B3%E3%83%BC%E3%83%89%E4%B8%80%E8%A6%A7)またはその[バリアント](internationalization)を使用。デフォルトは`en`。 -`timezone` | ウェブサイトのタイムゾーン。デフォルトではコンピューターの設定を使用。利用可能なタイムゾーンのリストは[こちら](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones)。例えば`America/New_York`、`Japan`、`UTC`など。 +| 設定 | 説明 | +| ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `title` | ウェブサイトのタイトル | +| `subtitle` | ウェブサイトのサブタイトル | +| `description` | ウェブサイトの説明 | +| `keywords` | ウェブサイトのキーワード。複数の値をサポート。 | +| `author` | あなたの名前 | +| `language` | ウェブサイトの言語。[2文字のISO-639-1コード](https://ja.wikipedia.org/wiki/ISO_639-1%E3%82%B3%E3%83%BC%E3%83%89%E4%B8%80%E8%A6%A7)またはその[バリアント](internationalization)を使用。デフォルトは`en`。 | +| `timezone` | ウェブサイトのタイムゾーン。デフォルトではコンピューターの設定を使用。利用可能なタイムゾーンのリストは[こちら](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones)。例えば`America/New_York`、`Japan`、`UTC`など。 | ### URL -設定 | 説明 | デフォルト ---- | --- | --- -`url` | ウェブサイトのURL。`http://`または`https://`で始まる必要があります。 | -`root` | ウェブサイトのルートディレクトリ | `urlのパス名` -`permalink` | 記事の[パーマリンク](permalinks.html)形式 | `:year/:month/:day/:title/` -`permalink_defaults` | パーマリンクの各セグメントのデフォルト値 | -`pretty_urls` | [`permalink`](permalinks.html)変数をプリティURLに書き換え | -`pretty_urls.trailing_index` | 末尾の`index.html`を削除する場合は`false`に設定 | `true` -`pretty_urls.trailing_html` | 末尾の`.html`を削除する場合は`false`に設定(`index.html`の末尾には適用されない) | `true` +| 設定 | 説明 | デフォルト | +| ---------------------------- | -------------------------------------------------------------------------------- | --------------------------- | +| `url` | ウェブサイトのURL。`http://`または`https://`で始まる必要があります。 | +| `root` | ウェブサイトのルートディレクトリ | `urlのパス名` | +| `permalink` | 記事の[パーマリンク](permalinks.html)形式 | `:year/:month/:day/:title/` | +| `permalink_defaults` | パーマリンクの各セグメントのデフォルト値 | +| `pretty_urls` | [`permalink`](permalinks.html)変数をプリティURLに書き換え | +| `pretty_urls.trailing_index` | 末尾の`index.html`を削除する場合は`false`に設定 | `true` | +| `pretty_urls.trailing_html` | 末尾の`.html`を削除する場合は`false`に設定(`index.html`の末尾には適用されない) | `true` | {% note info サブディレクトリ内のウェブサイト %} ウェブサイトがサブディレクトリ内にある場合(例: `http://example.org/blog`)は、`url`に`http://example.org/blog`を設定し、`root`を`/blog/`に設定します。 @@ -33,7 +34,7 @@ title: 設定 例: -``` yaml +```yaml # 例: page.permalinkがhttp://example.com/foo/bar/index.htmlの場合 pretty_urls: trailing_index: false @@ -42,20 +43,20 @@ pretty_urls: ### ディレクトリ -設定 | 説明 | デフォルト ---- | --- | --- -`source_dir` | ソースフォルダ。コンテンツが保存される場所 | `source` -`public_dir` | パブリックフォルダ。静的サイトが生成される場所 | `public` -`tag_dir` | タグディレクトリ | `tags` -`archive_dir` | アーカイブディレクトリ | `archives` -`category_dir` | カテゴリディレクトリ | `categories` -`code_dir` | コードを含むディレクトリ(`source_dir`のサブディレクトリ) | `downloads/code` -`i18n_dir` | i18nディレクトリ | `:lang` -`skip_render` | レンダリングせずに`public`に直接コピーされるパス。パスのマッチングに[glob表現](https://github.com/micromatch/micromatch#extended-globbing)を使用できます。 +| 設定 | 説明 | デフォルト | +| -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------- | +| `source_dir` | ソースフォルダ。コンテンツが保存される場所 | `source` | +| `public_dir` | パブリックフォルダ。静的サイトが生成される場所 | `public` | +| `tag_dir` | タグディレクトリ | `tags` | +| `archive_dir` | アーカイブディレクトリ | `archives` | +| `category_dir` | カテゴリディレクトリ | `categories` | +| `code_dir` | コードを含むディレクトリ(`source_dir`のサブディレクトリ) | `downloads/code` | +| `i18n_dir` | i18nディレクトリ | `:lang` | +| `skip_render` | レンダリングせずに`public`に直接コピーされるパス。パスのマッチングに[glob表現](https://github.com/micromatch/micromatch#extended-globbing)を使用できます。 | 例: -``` yaml +```yaml skip_render: "mypage/**/*" # `source/mypage/index.html` と `source/mypage/code.js` を変更せずに出力します。 @@ -66,45 +67,45 @@ skip_render: "_posts/test-post.md" ### 執筆 -設定 | 説明 | デフォルト ---- | --- | --- -`new_post_name` | 新しい記事のファイル名形式 | `:title.md` -`default_layout` | デフォルトのレイアウト | `post` -`titlecase` | タイトルをタイトルケースに変換するか? | `false` -`external_link` | 外部リンクを新しいタブで開くか? | -`external_link.enable` | 外部リンクを新しいタブで開くか? | `true` -`external_link.field` | `site`全体に適用するか?`post`のみか? | `site` -`external_link.exclude` | ホスト名を除外。該当する場合はサブドメインを指定、`www`も含む | `[]` -`filename_case` | ファイル名を `1`小文字; `2`大文字 に変換 | `0` -`render_drafts` | 下書きを表示するか? | `false` -`post_asset_folder` | [アセットフォルダ](asset-folders.html)を有効にするか? | `false` -`relative_link` | リンクをルートフォルダに対して相対的にするか? | `false` -`future` | 未来の記事を表示するか? | `true` -`syntax_highlighter` | コードブロックのシンタックスハイライト設定。使い方は[シンタックスハイライト](syntax-highlight)セクションを参照。 | `highlight.js` -`highlight` | コードブロックのシンタックスハイライト設定。使い方は[Highlight.js](syntax-highlight#Highlight-js)セクションを参照。 | -`prismjs` | コードブロックのシンタックスハイライト設定。使い方は[PrismJS](syntax-highlight#PrismJS)セクションを参照。 | +| 設定 | 説明 | デフォルト | +| ----------------------- | ------------------------------------------------------------------------------------------------------------------- | -------------- | +| `new_post_name` | 新しい記事のファイル名形式 | `:title.md` | +| `default_layout` | デフォルトのレイアウト | `post` | +| `titlecase` | タイトルをタイトルケースに変換するか? | `false` | +| `external_link` | 外部リンクを新しいタブで開くか? | +| `external_link.enable` | 外部リンクを新しいタブで開くか? | `true` | +| `external_link.field` | `site`全体に適用するか?`post`のみか? | `site` | +| `external_link.exclude` | ホスト名を除外。該当する場合はサブドメインを指定、`www`も含む | `[]` | +| `filename_case` | ファイル名を `1`小文字; `2`大文字 に変換 | `0` | +| `render_drafts` | 下書きを表示するか? | `false` | +| `post_asset_folder` | [アセットフォルダ](asset-folders.html)を有効にするか? | `false` | +| `relative_link` | リンクをルートフォルダに対して相対的にするか? | `false` | +| `future` | 未来の記事を表示するか? | `true` | +| `syntax_highlighter` | コードブロックのシンタックスハイライト設定。使い方は[シンタックスハイライト](syntax-highlight)セクションを参照。 | `highlight.js` | +| `highlight` | コードブロックのシンタックスハイライト設定。使い方は[Highlight.js](syntax-highlight#Highlight-js)セクションを参照。 | +| `prismjs` | コードブロックのシンタックスハイライト設定。使い方は[PrismJS](syntax-highlight#PrismJS)セクションを参照。 | ### ホームページの設定 -設定 | 説明 | デフォルト ---- | --- | --- -`index_generator` | [hexo-generator-index](https://github.com/hexojs/hexo-generator-index)による記事のアーカイブ生成 | -`index_generator.path` | ブログのインデックスページのパス | `''` -`index_generator.per_page` | 1ページあたりの記事数。 | `10` -`index_generator.order_by` | 記事の並び順。デフォルトでは日付降順(新しいものから古いものへ)。 | `-date` -`index_generator.pagination_dir` | URL形式。[ページネーション](#ページネーション)設定を参照。 | `page` +| 設定 | 説明 | デフォルト | +| -------------------------------- | ------------------------------------------------------------------------------------------------ | ---------- | +| `index_generator` | [hexo-generator-index](https://github.com/hexojs/hexo-generator-index)による記事のアーカイブ生成 | +| `index_generator.path` | ブログのインデックスページのパス | `''` | +| `index_generator.per_page` | 1ページあたりの記事数。 | `10` | +| `index_generator.order_by` | 記事の並び順。デフォルトでは日付降順(新しいものから古いものへ)。 | `-date` | +| `index_generator.pagination_dir` | URL形式。[ページネーション](#ページネーション)設定を参照。 | `page` | ### カテゴリー&タグ -設定 | 説明 | デフォルト ---- | --- | --- -`default_category` | デフォルトのカテゴリー | `uncategorized` -`category_map` | カテゴリースラッグを上書き | -`tag_map` | タグスラッグを上書き | +| 設定 | 説明 | デフォルト | +| ------------------ | -------------------------- | --------------- | +| `default_category` | デフォルトのカテゴリー | `uncategorized` | +| `category_map` | カテゴリースラッグを上書き | +| `tag_map` | タグスラッグを上書き | 例: -``` yaml +```yaml category_map: "yesterday's thoughts": yesterdays-thoughts "C++": c-plus-plus @@ -114,11 +115,11 @@ category_map: Hexoは日付の処理に[Moment.js](http://momentjs.com/)を使用します。 -設定 | 説明 | デフォルト ---- | --- | --- -`date_format` | 日付形式 | `YYYY-MM-DD` -`time_format` | 時刻形式 | `HH:mm:ss` -`updated_option` | Front Matterで提供されていない場合に使用する[`updated`](variables#ページ変数)の値 | `mtime` +| 設定 | 説明 | デフォルト | +| ---------------- | --------------------------------------------------------------------------------- | ------------ | +| `date_format` | 日付形式 | `YYYY-MM-DD` | +| `time_format` | 時刻形式 | `HH:mm:ss` | +| `updated_option` | Front Matterで提供されていない場合に使用する[`updated`](variables#ページ変数)の値 | `mtime` | {% note info updated_option %} `updated_option`はFront Matterで`updated`が指定されていない場合に`updated`の値を制御します: @@ -132,14 +133,14 @@ Hexoは日付の処理に[Moment.js](http://momentjs.com/)を使用します。 ### ページネーション -設定 | 説明 | デフォルト ---- | --- | --- -`per_page` | 各ページに表示される記事の数。`0`はページネーション無効化 | `10` -`pagination_dir` | URL形式 | `page` +| 設定 | 説明 | デフォルト | +| ---------------- | --------------------------------------------------------- | ---------- | +| `per_page` | 各ページに表示される記事の数。`0`はページネーション無効化 | `10` | +| `pagination_dir` | URL形式 | `page` | 例: -``` yaml +```yaml pagination_dir: 'page' # http://example.com/page/2 @@ -149,12 +150,12 @@ pagination_dir: 'awesome-page' ### 拡張機能 -設定 | 説明 ---- | --- -`theme` | テーマ名。`false`はテーマを無効にします -`theme_config` | テーマ設定。このキーの配下のカスタムテーマ設定は、テーマのデフォルトを上書きします。 -`deploy` | デプロイ設定 -`meta_generator` | [メタジェネレータ](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta#Attributes)タグ。`false`はタグの注入を無効にします。 +| 設定 | 説明 | +| ---------------- | -------------------------------------------------------------------------------------------------------------------------------------- | +| `theme` | テーマ名。`false`はテーマを無効にします | +| `theme_config` | テーマ設定。このキーの配下のカスタムテーマ設定は、テーマのデフォルトを上書きします。 | +| `deploy` | デプロイ設定 | +| `meta_generator` | [メタジェネレータ](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta#Attributes)タグ。`false`はタグの注入を無効にします。 | ### ファイルやフォルダーを含める/除外する @@ -162,11 +163,11 @@ pagination_dir: 'awesome-page' `include`および`exclude`オプションは`source/`フォルダーにのみ適用され、`ignore`オプションはすべてのフォルダーに適用されます。 -設定 | 説明 ---- | --- -`include` | 隠しファイル(名前がアンダースコアで始まるファイルやフォルダーを含む、例外あり*)を含める -`exclude` | ファイルやフォルダーを除外 -`ignore` | ファイルやフォルダーを無視 +| 設定 | 説明 | +| --------- | ------------------------------------------------------------------------------------------ | +| `include` | 隠しファイル(名前がアンダースコアで始まるファイルやフォルダーを含む、例外あり\*)を含める | +| `exclude` | ファイルやフォルダーを除外 | +| `ignore` | ファイルやフォルダーを無視 | 例: @@ -215,7 +216,7 @@ ignore: `hexo`コマンドに`--config`フラグを追加し、代替のYAMLまたはJSON設定ファイルへのパスを指定することで、カスタム設定ファイルパスを指定できます。または、複数のYAMLまたはJSONファイルのカンマ区切りリスト(スペースなし)を指定できます。 -``` bash +```bash # '_config.yml'の代わりに'custom.yml'を使用 $ hexo server --config custom.yml @@ -243,7 +244,7 @@ theme: "my-theme" theme_config: bio: "My awesome bio" foo: - bar: 'a' + bar: "a" ``` ```yml @@ -258,11 +259,11 @@ logo: "a-cool-image.png" ```json { - bio: "My awesome bio", - logo: "a-cool-image.png", - foo: { - bar: "a", - baz: "b" + "bio": "My awesome bio", + "logo": "a-cool-image.png", + "foo": { + "bar": "a", + "baz": "b" } } ``` @@ -282,7 +283,7 @@ theme: "my-theme" # _config.my-theme.yml bio: "My awesome bio" foo: - bar: 'a' + bar: "a" ``` ```yml @@ -297,11 +298,11 @@ logo: "a-cool-image.png" ```json { - bio: "My awesome bio", - logo: "a-cool-image.png", - foo: { - bar: "a", - baz: "b" + "bio": "My awesome bio", + "logo": "a-cool-image.png", + "foo": { + "bar": "a", + "baz": "b" } } ``` diff --git a/source/ja/docs/contributing.md b/source/ja/docs/contributing.md index 35c2aa5ef6..828907e5f9 100644 --- a/source/ja/docs/contributing.md +++ b/source/ja/docs/contributing.md @@ -18,7 +18,6 @@ title: 貢献 - ソフトタブを使用し、2スペースのインデントを使ってください。 - コンマを先頭に置かないでください。 - また、Hexoには独自の[ESLint設定](https://github.com/hexojs/eslint-config-hexo)があるため、貢献の際はESLintのルールに従っていることを確認してください。 ### ワークフロー @@ -26,7 +25,7 @@ title: 貢献 1. [hexojs/hexo]をフォークします。 2. リポジトリをコンピューターにクローンし、依存関係をインストールします。 -``` bash +```bash $ git clone https://github.com/<username>/hexo.git $ cd hexo $ npm install @@ -35,7 +34,7 @@ $ git submodule update --init 3. ブランチを作成します。 -``` bash +```bash $ git checkout -b new_feature ``` @@ -53,7 +52,7 @@ $ git push origin new_feature - `package.json`のバージョン番号は変更しないでください。 - プルリクエストは、テストが通った場合にのみマージされます。提出前にテストを実行してください。 -``` bash +```bash $ npm test ``` @@ -70,7 +69,7 @@ Hexoのドキュメントはオープンソースで、ソースコードは[hex 1. [hexojs/site]をフォークします。 2. リポジトリをコンピューターにクローンし、依存関係をインストールします。 -``` bash +```bash $ npm install hexo-cli -g # hexo-cliがインストールされていない場合 $ git clone https://github.com/<username>/site.git $ cd site @@ -79,7 +78,7 @@ $ npm install 3. ドキュメントの編集を始めます。ライブプレビューのためにサーバーを起動することができます。 -``` bash +```bash $ hexo server ``` diff --git a/source/ja/docs/data-files.md b/source/ja/docs/data-files.md index 23a8641aa0..2b747fcc87 100644 --- a/source/ja/docs/data-files.md +++ b/source/ja/docs/data-files.md @@ -1,11 +1,12 @@ --- title: データファイル --- + 記事から直接ではなく、テンプレートから利用するデータが必要になることがあります。データを他の場所で再利用したい場合もあるでしょう。このような用途のために、Hexo 3では新しい**データファイル**が導入されました。この機能は`source/_data`フォルダ内のYAMLまたはJSONファイルを読み込み、サイト内でそれらを使用できます。 例として、`source/_data`フォルダに`menu.yml`を追加します。 -``` yaml +```yaml Home: / Gallery: /gallery/ Archives: /archives/ diff --git a/source/ja/docs/front-matter.md b/source/ja/docs/front-matter.md index 54a8c78fc1..aa0c48b523 100644 --- a/source/ja/docs/front-matter.md +++ b/source/ja/docs/front-matter.md @@ -6,7 +6,7 @@ Front Matterは、ファイルの先頭に配置されるYAMLまたはJSONのブ **YAML** -``` yaml +```yaml --- title: Hello World date: 2013/7/13 20:46:25 @@ -15,7 +15,7 @@ date: 2013/7/13 20:46:25 **JSON** -``` json +```json "title": "Hello World", "date": "2013/7/13 20:46:25" ;;; @@ -23,20 +23,20 @@ date: 2013/7/13 20:46:25 ### 設定とデフォルト値 -設定 | 説明 | デフォルト ---- | --- | --- -`layout` | レイアウト | [`config.default_layout`](configuration#執筆) -`title` | タイトル | ファイル名(記事のみ) -`date` | 公開日 | ファイル作成日 -`updated` | 更新日 | ファイル更新日 -`comments` | 記事へのコメント機能を有効にする | `true` -`tags` | タグ(ページには利用不可) | -`categories` | カテゴリ(ページには利用不可) | -`permalink` | 記事のデフォルトパーマリンクを上書き。パーマリンクは`/`または`.html`で終わるべき | `null` -`excerpt` | プレーンテキストでのページの抜粋。テキストのフォーマットには[このプラグイン](tag-plugins#記事の抜粋)を使用 | -`disableNunjucks` | 有効にするとNunjucksタグ`{{ }}`/`{% %}`と[タグプラグイン](tag-plugins)のレンダリングを無効にする | false -`lang` | [自動検出](internationalization#パス)を上書きする言語を設定 | `_config.yml`から継承 -`published` | 記事を公開するか? | `_posts`配下の記事では`true`、`_draft`配下の記事では`false` +| 設定 | 説明 | デフォルト | +| ----------------- | ---------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------- | +| `layout` | レイアウト | [`config.default_layout`](configuration#執筆) | +| `title` | タイトル | ファイル名(記事のみ) | +| `date` | 公開日 | ファイル作成日 | +| `updated` | 更新日 | ファイル更新日 | +| `comments` | 記事へのコメント機能を有効にする | `true` | +| `tags` | タグ(ページには利用不可) | +| `categories` | カテゴリ(ページには利用不可) | +| `permalink` | 記事のデフォルトパーマリンクを上書き。パーマリンクは`/`または`.html`で終わるべき | `null` | +| `excerpt` | プレーンテキストでのページの抜粋。テキストのフォーマットには[このプラグイン](tag-plugins#記事の抜粋)を使用 | +| `disableNunjucks` | 有効にするとNunjucksタグ`{{ }}`/`{% %}`と[タグプラグイン](tag-plugins)のレンダリングを無効にする | false | +| `lang` | [自動検出](internationalization#パス)を上書きする言語を設定 | `_config.yml`から継承 | +| `published` | 記事を公開するか? | `_posts`配下の記事では`true`、`_draft`配下の記事では`false` | #### レイアウト @@ -50,24 +50,24 @@ date: 2013/7/13 20:46:25 **例** -``` yaml +```yaml categories: -- スポーツ -- 野球 + - スポーツ + - 野球 tags: -- 怪我 -- 乱闘 -- 衝撃 + - 怪我 + - 乱闘 + - 衝撃 ``` 複数のカテゴリ階層を適用したい場合は、カテゴリ名のリストを単一の名前の代わりに使用します。Hexoが記事でこのように定義されたカテゴリを見つけると、その記事の各カテゴリを独自の独立した階層として扱います。 **例** -``` yaml +```yaml categories: -- [スポーツ, 野球] -- [MLB, アメリカンリーグ, ボストン・レッドソックス] -- [MLB, アメリカンリーグ, ニューヨーク・ヤンキース] -- ライバル関係 + - [スポーツ, 野球] + - [MLB, アメリカンリーグ, ボストン・レッドソックス] + - [MLB, アメリカンリーグ, ニューヨーク・ヤンキース] + - ライバル関係 ``` diff --git a/source/ja/docs/generating.md b/source/ja/docs/generating.md index 6456368b29..f449af4891 100644 --- a/source/ja/docs/generating.md +++ b/source/ja/docs/generating.md @@ -1,9 +1,10 @@ --- title: 生成 --- + Hexoでの静的ファイルの生成は、とても簡単で高速です。 -``` bash +```bash $ hexo generate ``` @@ -11,7 +12,7 @@ $ hexo generate Hexoはファイルの変更を監視し、即座にファイルを再生成できます。HexoはファイルのSHA1チェックサムを比較し、ファイルの変更が検出された場合にのみ書き込みます。 -``` bash +```bash $ hexo generate --watch ``` @@ -19,7 +20,7 @@ $ hexo generate --watch 生成後にデプロイするには、以下のコマンドのいずれかを実行します。2つのコマンドの間に違いはありません。 -``` bash +```bash $ hexo generate --deploy $ hexo deploy --generate ``` diff --git a/source/ja/docs/github-pages.md b/source/ja/docs/github-pages.md index abb72922e0..7d4a2e997f 100644 --- a/source/ja/docs/github-pages.md +++ b/source/ja/docs/github-pages.md @@ -4,13 +4,15 @@ title: GitHub Pages このチュートリアルでは、[GitHub Actions](https://docs.github.com/en/actions) を使用して GitHub Pages をデプロイします。これはパブリックリポジトリとプライベートリポジトリの両方で機能します。ソースフォルダを GitHub にアップロードしたくない場合は、[ワンコマンドデプロイ](#ワンコマンド・デプロイ) セクションに進んでください。 -1. <b>*username*.github.io</b> という名前のリポジトリを作成します。username は GitHub 上のユーザー名です。他のリポジトリにアップロードしている場合は、リポジトリの名前を変更してください。 +1. <b>_username_.github.io</b> という名前のリポジトリを作成します。username は GitHub 上のユーザー名です。他のリポジトリにアップロードしている場合は、リポジトリの名前を変更してください。 2. Hexo フォルダのファイルをリポジトリのデフォルトブランチにプッシュします。デフォルトブランチは通常 **main** ですが、古いリポジトリでは **master** ブランチかもしれません。 + - GitHub に `main` ブランチをプッシュするには: - ``` - $ git push -u origin main - ``` + ``` + $ git push -u origin main + ``` + - `public/` フォルダはデフォルトでアップロードされません(されるべきではありません)。`.gitignore` ファイルに `public/` 行が含まれていることを確認してください。フォルダ構造は [このリポジトリ](https://github.com/hexojs/hexo-starter) 倣うべきです。 3. ローカルマシンで使用している Node.js のバージョンを `node --version` で確認し、メジャーバージョン(例: `v16.y.z`)を控えます。 @@ -23,7 +25,7 @@ name: Pages on: push: branches: - - main # default branch + - main # default branch jobs: build: @@ -37,7 +39,7 @@ jobs: - name: Use Node.js 16.x uses: actions/setup-node@v2 with: - node-version: '16' + node-version: "16" - name: Cache NPM dependencies uses: actions/cache@v2 with: @@ -68,7 +70,7 @@ jobs: uses: actions/deploy-pages@v2 ``` -6. デプロイが完了したら、*username*.github.io でウェブページを確認します。 +6. デプロイが完了したら、_username_.github.io でウェブページを確認します。 注 - `CNAME` でカスタムドメイン名を指定する場合は、`source/` フォルダに `CNAME` ファイルを追加する必要があります。[詳細情報](https://docs.github.com/ja/pages/configuring-a-custom-domain-for-your-github-pages-site/managing-a-custom-domain-for-your-github-pages-site)。 @@ -76,29 +78,29 @@ jobs: GitHub でプロジェクトページを持ちたい場合は: -1. GitHubリポジトリで**Settings** タブを表示します。**Repository name** を変更して、ブログが <b>username.github.io/*repository*</b> で利用できるようにします。**repository** は *blog* や *hexo* など任意の名前にできます。 -2. **_config.yml** を編集し、`url:` の値を <b>https://*username*.github.io/*repository*</b> に変更します。 +1. GitHubリポジトリで**Settings** タブを表示します。**Repository name** を変更して、ブログが <b>username.github.io/_repository_</b> で利用できるようにします。**repository** は _blog_ や _hexo_ など任意の名前にできます。 +2. **\_config.yml** を編集し、`url:` の値を <b>https://_username_.github.io/_repository_</b> に変更します。 3. GitHub リポジトリの設定で、**Settings** > **Pages** > **Source** に移動します。ソースを **GitHub Actions** に変更し保存します。 4. デフォルトブランチにコミットしてプッシュします。 -5. デプロイが完了したら、*username*.github.io/*repository* でウェブページを確認します。 +5. デプロイが完了したら、_username_.github.io/_repository_ でウェブページを確認します。 ## ワンコマンド・デプロイ 以下の説明は [ワンコマンド・デプロイ](../docs/one-command-deployment) からの抜粋です。 1. [hexo-deployer-git](https://github.com/hexojs/hexo-deployer-git) をインストールします。 -2. **_config.yml** に以下の設定を追加します(存在する場合は既存の行を修正します)。 - - ``` yml - deploy: - type: git - repo: https://github.com/<username>/<project> - # example, https://github.com/hexojs/hexojs.github.io - branch: gh-pages - ``` +2. **\_config.yml** に以下の設定を追加します(存在する場合は既存の行を修正します)。 + +```yml +deploy: + type: git + repo: https://github.com/<username>/<project> + # example, https://github.com/hexojs/hexojs.github.io + branch: gh-pages +``` 3. `hexo clean && hexo deploy` を実行します。 -4. *username*.github.io でウェブページを確認します。 +4. _username_.github.io でウェブページを確認します。 ## 便利なリンク diff --git a/source/ja/docs/gitlab-pages.md b/source/ja/docs/gitlab-pages.md index 66423ca9dc..14d3b905a1 100644 --- a/source/ja/docs/gitlab-pages.md +++ b/source/ja/docs/gitlab-pages.md @@ -2,13 +2,13 @@ title: GitLab Pages --- -1. <b>*username*.gitlab.io</b> という名前の新しいリポジトリを作成します。usernameはGitLab上のユーザー名です。他のリポジトリにアップロードしている場合は、リポジトリの名前を変更してください。 +1. <b>_username_.gitlab.io</b> という名前の新しいリポジトリを作成します。usernameはGitLab上のユーザー名です。他のリポジトリにアップロードしている場合は、リポジトリの名前を変更してください。 2. **Settings** > **CI/CD** > **Runners** > **Enable shared runners for this project** からShared Runnersを有効にします。 3. Hexoフォルダのファイルをリポジトリにプッシュします。`public/` フォルダはデフォルトでアップロードされません(されるべきではありません)、`.gitignore` ファイルに `public/` 行が含まれていることを確認してください。フォルダ構造は [このリポジトリ](https://github.com/hexojs/hexo-starter) 倣うべきです。 4. ローカルマシンで使用している Node.js のバージョンを `node --version` で確認し、メジャーバージョン(例: `v16.y.z`)を控えます。 5. リポジトリに以下の内容で `.github/workflows/pages.yml` を作成します(前のステップで控えた Node.js のメジャーバージョンに `16` を置き換えます): -``` yml +```yml image: node:16-alpine cache: paths: @@ -28,15 +28,15 @@ pages: - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH ``` -6. GitLab CIがデプロイジョブを終了すると、*username*.gitlab.io が動作しているはずです。 +6. GitLab CIがデプロイジョブを終了すると、_username_.gitlab.io が動作しているはずです。 7. (任意)生成されたサイトアセット(html、css、jsなど)は [ジョブアーティファクト](https://docs.gitlab.com/ee/ci/pipelines/job_artifacts.html) でから見つけることができます。 ## プロジェクトページ GitLab上でプロジェクトページを持ちたい場合は: -1. **Settings** > **General** > **Advanced** > **Change path** の設定を変更し、ウェブサイトが <b>username.gitlab.io/*repository*</b> で利用できるようにします。*blog* や *hexo* のように任意の名前にできます。 -2. **_config.yml** を編集し、`url:` の値を `https://username.gitlab.io/repository` に変更します。 +1. **Settings** > **General** > **Advanced** > **Change path** の設定を変更し、ウェブサイトが <b>username.gitlab.io/_repository_</b> で利用できるようにします。_blog_ や _hexo_ のように任意の名前にできます。 +2. **\_config.yml** を編集し、`url:` の値を `https://username.gitlab.io/repository` に変更します。 3. コミットしてプッシュします。 ## 便利なリンク diff --git a/source/ja/docs/helpers.md b/source/ja/docs/helpers.md index 0f2cea3209..25b88fc97e 100644 --- a/source/ja/docs/helpers.md +++ b/source/ja/docs/helpers.md @@ -1,6 +1,7 @@ --- title: ヘルパー --- + ヘルパーを使うことで、テンプレートにスニペットを素早く挿入できます。ソースファイル内では使用できません。 独自のカスタムヘルパーを簡単に[作成する](../api/helper.html)ほか、既に用意されているヘルパーを使うこともできます。 @@ -11,22 +12,22 @@ title: ヘルパー ルートパスが先頭に付与されたURLを返します。出力は自動的にエンコードされます。 -``` js +```js <%- url_for(path, [option]) %> ``` -オプション | 説明 | デフォルト ---- | --- | --- -`relative` | 相対リンクを出力 | `config.relative_link`の値 +| オプション | 説明 | デフォルト | +| ---------- | ---------------- | -------------------------- | +| `relative` | 相対リンクを出力 | `config.relative_link`の値 | **例:** -``` yml +```yml _config.yml root: /blog/ # example ``` -``` js +```js <%- url_for('/a/path') %> // /blog/a/path ``` @@ -34,12 +35,12 @@ root: /blog/ # example 相対リンクはデフォルトで`relative_link`オプションに従います。 例えば、記事やページのパスが '/foo/bar/index.html' の場合: -``` yml +```yml _config.yml relative_link: true ``` -``` js +```js <%- url_for('/css/style.css') %> // ../../css/style.css @@ -55,13 +56,13 @@ relative_link: true `from`から`to`への相対URLを返します。 -``` js +```js <%- relative_url(from, to) %> ``` **例:** -``` js +```js <%- relative_url('foo/bar/', 'css/style.css') %> // ../../css/style.css ``` @@ -70,18 +71,18 @@ relative_link: true `config.url`を先頭に付与したURLを返します。出力は自動的にエンコードされます。 -``` js +```js <%- full_url_for(path) %> ``` **例:** -``` yml +```yml _config.yml url: https://example.com/blog # example ``` -``` js +```js <%- full_url_for('/a/path') %> // https://example.com/blog/a/path ``` @@ -92,22 +93,22 @@ url: https://example.com/blog # example [options] パラメータを指定しない場合、デフォルトのオプションが適用されます。指定する場合、サイズパラメータとして Gravatar に渡される数値を設定します。最後に、これをオブジェクトに設定すると、Gravatar のパラメーターのクエリ文字列に変換されます。 -``` js +```js <%- gravatar(email, [options]) %> ``` -オプション | 説明 | デフォルト ---- | --- | --- -`s` | 出力する画像サイズ | 80 -`d` | デフォルト画像 | -`f` | デフォルトを強制 | -`r` | レーティング | +| オプション | 説明 | デフォルト | +| ---------- | ------------------ | ---------- | +| `s` | 出力する画像サイズ | 80 | +| `d` | デフォルト画像 | +| `f` | デフォルトを強制 | +| `r` | レーティング | 詳細: [Gravatar](https://en.gravatar.com/site/implement/images/) **例:** -``` js +```js <%- gravatar('a@abc.com') %> // https://www.gravatar.com/avatar/b9b00e66c6b8a70f88c73cb6bdb06787 @@ -124,13 +125,13 @@ url: https://example.com/blog # example CSSファイルを読み込みます。 `path` には文字列、配列、オブジェクト、またはオブジェクトの配列を指定できます。[`/<root>/`](configuration#URL)の値が先頭に付与され、`.css` 拡張子が `path` に追加されます。カスタム属性にはオブジェクトを指定します。 -``` js +```js <%- css(path, ...) %> ``` **例:** -``` js +```js <%- css('style.css') %> // <link rel="stylesheet" href="/style.css"> @@ -148,15 +149,15 @@ CSSファイルを読み込みます。 `path` には文字列、配列、オブ ### js -JavaScriptファイルを読み込みます。 `path` には文字列、配列、オブジェクト、またはオブジェクトの配列を指定できます。[`/<root>/`](configuration#URL)の値が先頭に付与され、`.js` 拡張子が `path` に追加されます。カスタム属性にはオブジェクトを指定します。 +JavaScriptファイルを読み込みます。 `path` には文字列、配列、オブジェクト、またはオブジェクトの配列を指定できます。[`/<root>/`](configuration#URL)の値が先頭に付与され、`.js` 拡張子が `path` に追加されます。カスタム属性にはオブジェクトを指定します。 -``` js +```js <%- js(path, ...) %> ``` **例:** -``` js +```js <%- js('script.js') %> // <script src="/script.js"></script> @@ -176,19 +177,19 @@ JavaScriptファイルを読み込みます。 `path` には文字列、配列 リンクを挿入します。 -``` js +```js <%- link_to(path, [text], [options]) %> ``` -オプション | 説明 | デフォルト ---- | --- | --- -`external` | リンクを新しいタブで開くか? | false -`class` | クラス名 | -`id` | ID | +| オプション | 説明 | デフォルト | +| ---------- | ---------------------------- | ---------- | +| `external` | リンクを新しいタブで開くか? | false | +| `class` | クラス名 | +| `id` | ID | **例:** -``` js +```js <%- link_to('http://www.google.com') %> // <a href="http://www.google.com" title="http://www.google.com">http://www.google.com</a> @@ -203,22 +204,22 @@ JavaScriptファイルを読み込みます。 `path` には文字列、配列 メールリンクを挿入します。 -``` js +```js <%- mail_to(path, [text], [options]) %> ``` -オプション | 説明 ---- | --- -`class` | クラス名 -`id` | ID -`subject` | メールの件名 -`cc` | CC -`bcc` | BCC -`body` | メールの内容 +| オプション | 説明 | +| ---------- | ------------ | +| `class` | クラス名 | +| `id` | ID | +| `subject` | メールの件名 | +| `cc` | CC | +| `bcc` | BCC | +| `body` | メールの内容 | **例:** -``` js +```js <%- mail_to('a@abc.com') %> // <a href="mailto:a@abc.com" title="a@abc.com">a@abc.com</a> @@ -230,23 +231,23 @@ JavaScriptファイルを読み込みます。 `path` には文字列、配列 画像を挿入します。 -``` js +```js <%- image_tag(path, [options]) %> ``` -オプション | 説明 ---- | --- -`alt` | 画像の代替テキスト -`class` | クラス名 -`id` | ID -`width` | 画像の幅 -`height` | 画像の高さ +| オプション | 説明 | +| ---------- | ------------------ | +| `alt` | 画像の代替テキスト | +| `class` | クラス名 | +| `id` | ID | +| `width` | 画像の幅 | +| `height` | 画像の高さ | ### favicon_tag ファビコンを挿入します。 -``` js +```js <%- favicon_tag(path) %> ``` @@ -254,18 +255,18 @@ JavaScriptファイルを読み込みます。 `path` には文字列、配列 フィードリンクを挿入します。 -``` js +```js <%- feed_tag(path, [options]) %> ``` -オプション | 説明 | デフォルト ---- | --- | --- -`title` | フィードのタイトル | `config.title` -`type` | フィードのタイプ | +| オプション | 説明 | デフォルト | +| ---------- | ------------------ | -------------- | +| `title` | フィードのタイトル | `config.title` | +| `type` | フィードのタイプ | **例:** -``` js +```js <%- feed_tag('atom.xml') %> // <link rel="alternate" href="/atom.xml" title="Hexo" type="application/atom+xml"> @@ -283,7 +284,7 @@ JavaScriptファイルを読み込みます。 `path` には文字列、配列 `path`が現在のページのURLと一致するかチェックします。厳密な比較を行う場合`strict`オプションを指定します。 -``` js +```js <%- is_current(path, [strict]) %> ``` @@ -291,7 +292,7 @@ JavaScriptファイルを読み込みます。 `path` には文字列、配列 現在のページがホームページかチェックします。 -``` js +```js <%- is_home() %> ``` @@ -299,7 +300,7 @@ JavaScriptファイルを読み込みます。 `path` には文字列、配列 現在のページがホームページの最初のページかチェックします。 -``` js +```js <%- is_home_first_page() %> ``` @@ -307,7 +308,7 @@ JavaScriptファイルを読み込みます。 `path` には文字列、配列 現在のページが記事ページかチェックします。 -``` js +```js <%- is_post() %> ``` @@ -315,7 +316,7 @@ JavaScriptファイルを読み込みます。 `path` には文字列、配列 現在のページが固定ページかチェックします。 -``` js +```js <%- is_page() %> ``` @@ -323,7 +324,7 @@ JavaScriptファイルを読み込みます。 `path` には文字列、配列 現在のページがアーカイブページかチェックします。 -``` js +```js <%- is_archive() %> ``` @@ -331,7 +332,7 @@ JavaScriptファイルを読み込みます。 `path` には文字列、配列 現在のページが年別アーカイブページかチェックします。 -``` js +```js <%- is_year() %> ``` @@ -339,7 +340,7 @@ JavaScriptファイルを読み込みます。 `path` には文字列、配列 現在のページが月別アーカイブページかチェックします。 -``` js +```js <%- is_month() %> ``` @@ -348,7 +349,7 @@ JavaScriptファイルを読み込みます。 `path` には文字列、配列 現在のページがカテゴリーページかチェックします。 パラメータとして文字列が与えられた場合、現在のページが与えられたカテゴリーと一致するかチェックします。 -``` js +```js <%- is_category() %> <%- is_category('hobby') %> ``` @@ -358,7 +359,7 @@ JavaScriptファイルを読み込みます。 `path` には文字列、配列 現在のページがタグページかチェックします。 パラメータとして文字列が与えられた場合、現在のページが与えられたタグと一致するかチェックします。 -``` js +```js <%- is_tag() %> <%- is_tag('hobby') %> ``` @@ -369,7 +370,7 @@ JavaScriptファイルを読み込みます。 `path` には文字列、配列 文字列の前後の空白を除去します。 -``` js +```js <%- trim(string) %> ``` @@ -377,13 +378,13 @@ JavaScriptファイルを読み込みます。 `path` には文字列、配列 文字列からすべてのHTMLタグを除去します。 -``` js +```js <%- strip_html(string) %> ``` **例:** -``` js +```js <%- strip_html('It\'s not <b>important</b> anymore!') %> // It's not important anymore! ``` @@ -392,13 +393,13 @@ JavaScriptファイルを読み込みます。 `path` には文字列、配列 文字列をタイトルケースに変換します。 -``` js +```js <%- titlecase(string) %> ``` **例:** -``` js +```js <%- titlecase('this is an apple') %> # This is an Apple ``` @@ -407,13 +408,13 @@ JavaScriptファイルを読み込みます。 `path` には文字列、配列 Markdown文字列をレンダリングします。 -``` js +```js <%- markdown(str) %> ``` **例:** -``` js +```js <%- markdown('make me **strong**') %> // make me <strong>strong</strong> ``` @@ -422,13 +423,13 @@ Markdown文字列をレンダリングします。 文字列をレンダリングします。 -``` js +```js <%- render(str, engine, [options]) %> ``` **例:** -``` js +```js <%- render('p(class="example") Test', 'pug'); %> // <p class="example">Test</p> ``` @@ -439,13 +440,13 @@ Markdown文字列をレンダリングします。 テキストを指定された`length`以内に折り返します。`length`はデフォルトで80です。 -``` js +```js <%- word_wrap(str, [length]) %> ``` **例:** -``` js +```js <%- word_wrap('Once upon a time', 8) %> // Once upon\n a time ``` @@ -454,13 +455,13 @@ Markdown文字列をレンダリングします。 テキストを指定された`length`以内に切り捨てます。デフォルトは30文字です。 -``` js +```js <%- truncate(text, [options]) %> ``` **例:** -``` js +```js <%- truncate('Once upon a time in a world far far away', {length: 17}) %> // Once upon a ti... @@ -475,13 +476,13 @@ Markdown文字列をレンダリングします。 文字列中のHTMLエンティティをエスケープします。 -``` js +```js <%- escape_html(str) %> ``` **例:** -``` js +```js <%- escape_html('<p>Hello "world".</p>') %> // <p>Hello "world".</p> ``` @@ -492,26 +493,26 @@ Markdown文字列をレンダリングします。 他のテンプレートファイルを読み込みます。`locals`でローカル変数を定義できます。 -``` js +```js <%- partial(layout, [locals], [options]) %> ``` -オプション | 説明 | デフォルト ---- | --- | --- -`cache` | コンテンツをキャッシュします(フラグメントキャッシュを使用) | `false` -`only` | 厳格なローカル変数。テンプレート内で`locals`に設定された変数のみを使用します。 | `false` +| オプション | 説明 | デフォルト | +| ---------- | ------------------------------------------------------------------------------ | ---------- | +| `cache` | コンテンツをキャッシュします(フラグメントキャッシュを使用) | `false` | +| `only` | 厳格なローカル変数。テンプレート内で`locals`に設定された変数のみを使用します。 | `false` | ### fragment_cache フラグメント内のコンテンツをキャッシュし、以降のリクエストではそれを使います。 -``` js +```js <%- fragment_cache(id, fn); ``` **例:** -``` js +```js <%- fragment_cache('header', function(){ return '<header></header>'; }) %> @@ -523,13 +524,13 @@ Markdown文字列をレンダリングします。 フォーマットされた日付を挿入します。`date`にはunix時刻、ISO文字列、Dateオブジェクト、または[Moment.js]オブジェクトを指定できます。`format`はデフォルトで`date_format`設定が使われます。 -``` js +```js <%- date(date, [format]) %> ``` **例:** -``` js +```js <%- date(Date.now()) %> // 2013-01-01 @@ -541,13 +542,13 @@ Markdown文字列をレンダリングします。 XMLフォーマットで日付を挿入します。`date`にはunix時刻、ISO文字列、Dateオブジェクト、または[Moment.js]オブジェクトを指定できます。 -``` js +```js <%- date_xml(date) %> ``` **例:** -``` js +```js <%- date_xml(Date.now()) %> // 2013-01-01T00:00:00.000Z ``` @@ -556,13 +557,13 @@ XMLフォーマットで日付を挿入します。`date`にはunix時刻、ISO フォーマットされた時刻を挿入します。`date`にはunix時刻、ISO文字列、Dateオブジェクト、または[Moment.js]オブジェクトを指定できます。`format`はデフォルトで`time_format`設定が使われます。 -``` js +```js <%- time(date, [format]) %> ``` **例:** -``` js +```js <%- time(Date.now()) %> // 13:05:12 @@ -574,13 +575,13 @@ XMLフォーマットで日付を挿入します。`date`にはunix時刻、ISO フォーマットされた日付と時刻を挿入します。`date`にはunix時刻、ISO文字列、Dateオブジェクト、または[Moment.js]オブジェクトを指定できます。`format`はデフォルトで`date_format + time_format`の設定が使われます。 -``` js +```js <%- full_date(date, [format]) %> ``` **例:** -``` js +```js <%- full_date(new Date()) %> // Jan 1, 2013 0:00:00 @@ -598,7 +599,7 @@ XMLフォーマットで日付を挿入します。`date`にはunix時刻、ISO **例:** -``` js +```js <%- relative_date(new Date()) %> // a few seconds ago @@ -616,7 +617,7 @@ timeタグを挿入します。`date`にはunix時刻、ISO文字列、Dateオ **例:** -``` js +```js <%- time_tag(new Date()) %> // <time datetime="2024-01-22T06:35:31.108Z">2024-01-22</time> @@ -634,25 +635,25 @@ timeタグを挿入します。`date`にはunix時刻、ISO文字列、Dateオ カテゴリの一覧を挿入します。 -``` js +```js <%- list_categories([options]) %> ``` -オプション | 説明 | デフォルト ---- | --- | --- -`orderby` | カテゴリの順序 | name -`order` | 並び順。`1`,`asc` で昇順;`-1`,`desc` で降順 | 1 -`show_count` | 各カテゴリの記事数を表示するか? | true -`style` | 一覧の表示スタイル。`list` は順序なしリストでカテゴリを表示。`false` または他の値で無効化。 | list -`separator` | カテゴリの区切り文字。(`style` が `list` でない場合のみ機能) | , -`depth` | 表示するカテゴリのレベル。`0` で全カテゴリと子カテゴリを表示;`-1` は `0` と同様だがフラットに表示;`1` でトップレベルのカテゴリのみ表示。 | 0 -`class` | 一覧のクラス名。 | category -`transform` | カテゴリ名の表示を変更する関数。 | -`suffix` | リンクに接尾辞を追加。 | なし +| オプション | 説明 | デフォルト | +| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------ | ---------- | +| `orderby` | カテゴリの順序 | name | +| `order` | 並び順。`1`,`asc` で昇順;`-1`,`desc` で降順 | 1 | +| `show_count` | 各カテゴリの記事数を表示するか? | true | +| `style` | 一覧の表示スタイル。`list` は順序なしリストでカテゴリを表示。`false` または他の値で無効化。 | list | +| `separator` | カテゴリの区切り文字。(`style` が `list` でない場合のみ機能) | , | +| `depth` | 表示するカテゴリのレベル。`0` で全カテゴリと子カテゴリを表示;`-1` は `0` と同様だがフラットに表示;`1` でトップレベルのカテゴリのみ表示。 | 0 | +| `class` | 一覧のクラス名。 | category | +| `transform` | カテゴリ名の表示を変更する関数。 | +| `suffix` | リンクに接尾辞を追加。 | なし | **例:** -``` js +```js <%- list_categories(post.categories, { class: 'post-category', transform(str) { @@ -672,31 +673,31 @@ timeタグを挿入します。`date`にはunix時刻、ISO文字列、Dateオ タグの一覧を挿入します。 -``` js +```js <%- list_tags([options]) %> ``` -オプション | 説明 | デフォルト ---- | --- | --- -`orderby` | タグの順序 | name -`order` | 並び順。`1`,`asc` で昇順;`-1`,`desc` で降順 | 1 -`show_count` | 各タグの記事数を表示するか? | true -`style` | 一覧の表示スタイル。`list` は順序なしリストでタグを表示。`false` または他の値で無効化。 | list -`separator` | タグの区切り文字。(`style` が `list` でない場合のみ機能) | , -`class` | 一覧のクラス名(文字列)または各タグのクラスをカスタマイズ(オブジェクト、以下を参照)。 | tag -`transform` | タグ名の表示を変更する関数。[list_categories](#list-categories) の例を参照。 | -`amount` | 表示するタグの数(0 = 無制限) | 0 -`suffix` | リンクに接尾辞を追加。 | なし +| オプション | 説明 | デフォルト | +| ------------ | ---------------------------------------------------------------------------------------- | ---------- | +| `orderby` | タグの順序 | name | +| `order` | 並び順。`1`,`asc` で昇順;`-1`,`desc` で降順 | 1 | +| `show_count` | 各タグの記事数を表示するか? | true | +| `style` | 一覧の表示スタイル。`list` は順序なしリストでタグを表示。`false` または他の値で無効化。 | list | +| `separator` | タグの区切り文字。(`style` が `list` でない場合のみ機能) | , | +| `class` | 一覧のクラス名(文字列)または各タグのクラスをカスタマイズ(オブジェクト、以下を参照)。 | tag | +| `transform` | タグ名の表示を変更する関数。[list_categories](#list-categories) の例を参照。 | +| `amount` | 表示するタグの数(0 = 無制限) | 0 | +| `suffix` | リンクに接尾辞を追加。 | なし | クラスの高度なカスタマイズ: -オプション | 説明 | デフォルト ---- | --- | --- -`class.ul` | `<ul>` のクラス名(`list` スタイルのみ) | `tag-list` (`list` スタイル) -`class.li` | `<li>` のクラス名(`list` スタイルのみ) | `tag-list-item` (`list` スタイル) -`class.a` | `<a>` のクラス名 | `tag-list-link` (`list` スタイル) `tag-link` (通常スタイル) -`class.label` | タグラベルを格納する `<span>` のクラス名(通常スタイルで`class.label` が設定されている場合のみ、ラベルは `<span>` に入れられます) | `tag-label` (通常スタイル) -`class.count` | タグカウンタが格納される `<span>` のクラス名(`show_count` が `true` の場合のみ) | `tag-list-count` (`list` スタイル) `tag-count` (通常スタイル) +| オプション | 説明 | デフォルト | +| ------------- | ---------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------- | +| `class.ul` | `<ul>` のクラス名(`list` スタイルのみ) | `tag-list` (`list` スタイル) | +| `class.li` | `<li>` のクラス名(`list` スタイルのみ) | `tag-list-item` (`list` スタイル) | +| `class.a` | `<a>` のクラス名 | `tag-list-link` (`list` スタイル) `tag-link` (通常スタイル) | +| `class.label` | タグラベルを格納する `<span>` のクラス名(通常スタイルで`class.label` が設定されている場合のみ、ラベルは `<span>` に入れられます) | `tag-label` (通常スタイル) | +| `class.count` | タグカウンタが格納される `<span>` のクラス名(`show_count` が `true` の場合のみ) | `tag-list-count` (`list` スタイル) `tag-count` (通常スタイル) | 例: @@ -711,66 +712,66 @@ timeタグを挿入します。`date`にはunix時刻、ISO文字列、Dateオ アーカイブの一覧を挿入します。 -``` js +```js <%- list_archives([options]) %> ``` -オプション | 説明 | デフォルト ---- | --- | --- -`type` | 一覧の種類。`yearly` または `monthly` を指定できます。 | monthly -`order` | 並び順。`1`,`asc` で昇順;`-1`,`desc` で降順 | 1 -`show_count` | 各アーカイブの記事数を表示するか? | true -`format` | 日付の形式 | MMMM YYYY -`style` | 一覧の表示スタイル。`list` は順序なしリストでアーカイブを表示。`false` または他の値で無効化。 | list -`separator` | アーカイブの区切り文字。(`style` が `list` でない場合のみ機能) | , -`class` | 一覧のクラス名。 | archive -`transform` | アーカイブ名の表示を変更する関数。[list_categories](#list-categories) の例を参照。 | +| オプション | 説明 | デフォルト | +| ------------ | --------------------------------------------------------------------------------------------- | ---------- | +| `type` | 一覧の種類。`yearly` または `monthly` を指定できます。 | monthly | +| `order` | 並び順。`1`,`asc` で昇順;`-1`,`desc` で降順 | 1 | +| `show_count` | 各アーカイブの記事数を表示するか? | true | +| `format` | 日付の形式 | MMMM YYYY | +| `style` | 一覧の表示スタイル。`list` は順序なしリストでアーカイブを表示。`false` または他の値で無効化。 | list | +| `separator` | アーカイブの区切り文字。(`style` が `list` でない場合のみ機能) | , | +| `class` | 一覧のクラス名。 | archive | +| `transform` | アーカイブ名の表示を変更する関数。[list_categories](#list-categories) の例を参照。 | ### list_posts 記事の一覧を挿入します。 -``` js +```js <%- list_posts([options]) %> ``` -オプション | 説明 | デフォルト ---- | --- | --- -`orderby` | 記事の順序 | date -`order` | 並び順。`1`,`asc` で昇順;`-1`,`desc` で降順 | 1 -`style` | 一覧の表示スタイル。`list` は順序なしリストで記事を表示。`false` または他の値で無効化。 | list -`separator` | 記事の区切り文字。(`style` が `list` でない場合のみ機能) | , -`class` | 一覧のクラス名。 | post -`amount` | 表示する記事の数(0 = 無制限) | 6 -`transform` | 記事名の表示を変更する関数。[list_categories](#list-categories) の例を参照。 | +| オプション | 説明 | デフォルト | +| ----------- | --------------------------------------------------------------------------------------- | ---------- | +| `orderby` | 記事の順序 | date | +| `order` | 並び順。`1`,`asc` で昇順;`-1`,`desc` で降順 | 1 | +| `style` | 一覧の表示スタイル。`list` は順序なしリストで記事を表示。`false` または他の値で無効化。 | list | +| `separator` | 記事の区切り文字。(`style` が `list` でない場合のみ機能) | , | +| `class` | 一覧のクラス名。 | post | +| `amount` | 表示する記事の数(0 = 無制限) | 6 | +| `transform` | 記事名の表示を変更する関数。[list_categories](#list-categories) の例を参照。 | ### tagcloud タグクラウドを挿入します。 -``` js +```js <%- tagcloud([tags], [options]) %> ``` -オプション | 説明 | デフォルト ---- | --- | --- -`min_font` | 最小フォントサイズ | 10 -`max_font` | 最大フォントサイズ | 20 -`unit` | フォントサイズの単位 | px -`amount` | タグの総数 | 無制限 -`orderby` | タグの順序 | name -`order` | 並び順。`1`,`asc` で昇順;`-1`,`desc` で降順 | 1 -`color` | タグクラウドを色付けするか? | false -`start_color` | 開始色。hex (`#b700ff`), rgba (`rgba(183, 0, 255, 1)`), hsla (`hsla(283, 100%, 50%, 1)`) または [色キーワード] を指定可能。このオプションは `color` が true の場合のみ機能します。 | -`end_color` | 終了色。hex (`#b700ff`), rgba (`rgba(183, 0, 255, 1)`), hsla (`hsla(283, 100%, 50%, 1)`) または [色キーワード] を指定可能。このオプションは `color` が true の場合のみ機能します。 | -`class` | タグのクラス名の接頭辞 -`level` | 異なるクラス名の数。このオプションは `class` が設定されている場合のみ機能します。 | 10 -`show_count` (6.3.0以上) | 各タグの記事数を表示 | false -`count_class` (6.3.0以上) | タグカウントのクラス名 | count +| オプション | 説明 | デフォルト | +| ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | +| `min_font` | 最小フォントサイズ | 10 | +| `max_font` | 最大フォントサイズ | 20 | +| `unit` | フォントサイズの単位 | px | +| `amount` | タグの総数 | 無制限 | +| `orderby` | タグの順序 | name | +| `order` | 並び順。`1`,`asc` で昇順;`-1`,`desc` で降順 | 1 | +| `color` | タグクラウドを色付けするか? | false | +| `start_color` | 開始色。hex (`#b700ff`), rgba (`rgba(183, 0, 255, 1)`), hsla (`hsla(283, 100%, 50%, 1)`) または [色キーワード] を指定可能。このオプションは `color` が true の場合のみ機能します。 | +| `end_color` | 終了色。hex (`#b700ff`), rgba (`rgba(183, 0, 255, 1)`), hsla (`hsla(283, 100%, 50%, 1)`) または [色キーワード] を指定可能。このオプションは `color` が true の場合のみ機能します。 | +| `class` | タグのクラス名の接頭辞 | +| `level` | 異なるクラス名の数。このオプションは `class` が設定されている場合のみ機能します。 | 10 | +| `show_count` (6.3.0以上) | 各タグの記事数を表示 | false | +| `count_class` (6.3.0以上) | タグカウントのクラス名 | count | **例:** -``` js +```js // デフォルトオプション <%- tagcloud() %> @@ -784,42 +785,41 @@ timeタグを挿入します。`date`にはunix時刻、ISO文字列、Dateオ ページネーターを挿入します。 -``` js +```js <%- paginator(options) %> ``` -オプション | 説明 | デフォルト ---- | --- | --- -`base` | ベースURL | / -`format` | URL形式 | page/%d/ -`total` | ページの総数 | 1 -`current` | 現在のページ番号 | 0 -`prev_text` | 前のページへのリンクテキスト。`prev_next`がtrueに設定されている場合のみ機能します。 | Prev -`next_text` | 次のページへのリンクテキスト。`prev_next`がtrueに設定されている場合のみ機能します。 | Next -`space` | スペーステキスト | … -`prev_next` | 前後のリンクを表示するか? | true -`end_size` | 開始と終了の直前と直後に表示されるページの数 | 1 -`mid_size` | 現在のページの前後に表示されるページの数 | 2 -`show_all` | すべてのページを表示するか?これがtrueに設定されている場合、`end_size`と`mid_size`は機能しません | false -`escape` | HTMLタグをエスケープ | true -`page_class` (6.3.0以上) | ページクラス名 | `page-number` -`current_class` (6.3.0以上) | 現在のページクラス名 | `current` -`space_class` (6.3.0以上) | スペースクラス名 | `space` -`prev_class` (6.3.0以上) | 前のページクラス名 | `extend prev` -`next_class` (6.3.0以上) | 次のページクラス名 | `extend next` -`force_prev_next` (6.3.0以上) | 前後のリンクを強制的に表示 | false - +| オプション | 説明 | デフォルト | +| ----------------------------- | ------------------------------------------------------------------------------------------------ | ------------- | +| `base` | ベースURL | / | +| `format` | URL形式 | page/%d/ | +| `total` | ページの総数 | 1 | +| `current` | 現在のページ番号 | 0 | +| `prev_text` | 前のページへのリンクテキスト。`prev_next`がtrueに設定されている場合のみ機能します。 | Prev | +| `next_text` | 次のページへのリンクテキスト。`prev_next`がtrueに設定されている場合のみ機能します。 | Next | +| `space` | スペーステキスト | … | +| `prev_next` | 前後のリンクを表示するか? | true | +| `end_size` | 開始と終了の直前と直後に表示されるページの数 | 1 | +| `mid_size` | 現在のページの前後に表示されるページの数 | 2 | +| `show_all` | すべてのページを表示するか?これがtrueに設定されている場合、`end_size`と`mid_size`は機能しません | false | +| `escape` | HTMLタグをエスケープ | true | +| `page_class` (6.3.0以上) | ページクラス名 | `page-number` | +| `current_class` (6.3.0以上) | 現在のページクラス名 | `current` | +| `space_class` (6.3.0以上) | スペースクラス名 | `space` | +| `prev_class` (6.3.0以上) | 前のページクラス名 | `extend prev` | +| `next_class` (6.3.0以上) | 次のページクラス名 | `extend next` | +| `force_prev_next` (6.3.0以上) | 前後のリンクを強制的に表示 | false | **例:** -``` js +```js <%- paginator({ prev_text: '<', next_text: '>' }) %> ``` -``` html +```html <!-- Rendered as --> <a href="/1/"><</a> <a href="/1/">1</a> @@ -828,7 +828,7 @@ timeタグを挿入します。`date`にはunix時刻、ISO文字列、Dateオ <a href="/3/">></a> ``` -``` js +```js <%- paginator({ prev_text: '<i class="fa fa-angle-left"></i>', next_text: '<i class="fa fa-angle-right"></i>', @@ -836,7 +836,7 @@ timeタグを挿入します。`date`にはunix時刻、ISO文字列、Dateオ }) %> ``` -``` html +```html <!-- Rendered as --> <a href="/1/"><i class="fa fa-angle-left"></i></a> <a href="/1/">1</a> @@ -849,33 +849,33 @@ timeタグを挿入します。`date`にはunix時刻、ISO文字列、Dateオ Google検索フォームを挿入します。 -``` js +```js <%- search_form(options) %> ``` -オプション | 説明 | デフォルト ---- | --- | --- -`class` | フォームのクラス名 | search-form -`text` | 検索ヒントワード | Search -`button` | 検索ボタンを表示。booleanまたはstringを指定できます。stringの場合はボタンのテキストになります。 | false +| オプション | 説明 | デフォルト | +| ---------- | ----------------------------------------------------------------------------------------------- | ----------- | +| `class` | フォームのクラス名 | search-form | +| `text` | 検索ヒントワード | Search | +| `button` | 検索ボタンを表示。booleanまたはstringを指定できます。stringの場合はボタンのテキストになります。 | false | ### number_format 数値をフォーマットします。 -``` js +```js <%- number_format(number, [options]) %> ``` -オプション | 説明 | デフォルト ---- | --- | --- -`precision` | 数値の精度。`false`または非負の整数を指定。 | false -`delimiter` | 千の位の区切り文字 | , -`separator` | 整数部と小数部を分けるセパレータ | . +| オプション | 説明 | デフォルト | +| ----------- | ------------------------------------------- | ---------- | +| `precision` | 数値の精度。`false`または非負の整数を指定。 | false | +| `delimiter` | 千の位の区切り文字 | , | +| `separator` | 整数部と小数部を分けるセパレータ | . | **例:** -``` js +```js <%- number_format(12345.67, {precision: 1}) %> // 12,345.68 @@ -896,13 +896,13 @@ Google検索フォームを挿入します。 [generator タグ](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta)を挿入します。 -``` js +```js <%- meta_generator() %> ``` **例:** -``` js +```js <%- meta_generator() %> // <meta name="generator" content="Hexo 4.0.0"> ``` @@ -911,54 +911,54 @@ Google検索フォームを挿入します。 [Open Graph] データを挿入します。 -``` js +```js <%- open_graph([options]) %> ``` -オプション | 説明 | デフォルト ---- | --- | --- -`title` | ページタイトル (`og:title`) | `page.title` -`type` | ページタイプ (`og:type`) | article(記事ページ)<br>website(記事ページ以外) -`url` | ページURL (`og:url`) | `url` -`image` | ページ画像 (`og:image`) | コンテンツ内の全画像 -`author` | 記事の著者 (`og:article:author`) | `config.author` -`date` | 記事の公開時刻 (`og:article:published_time`) | ページの公開時刻 -`updated` | 記事の更新時刻 (`og:article:modified_time`) | ページの更新時刻 -`language` | 記事の言語 (`og:locale`) | `page.lang \|\| page.language \|\| config.language` -`site_name` | サイト名 (`og:site_name`) | `config.title` -`description` | ページの説明 (`og:description`) | ページの抜粋またはコンテンツの最初の200文字 -`twitter_card` | Twitter カードタイプ (`twitter:card`) | summary -`twitter_id` | Twitter ID (`twitter:creator`) | -`twitter_site` | Twitter サイト (`twitter:site`) | -`twitter_image` | Twitter 画像 (`twitter:image`) | -`google_plus` | Google+ プロフィールリンク | -`fb_admins` | Facebook 管理者ID | -`fb_app_id` | Facebook アプリID | +| オプション | 説明 | デフォルト | +| --------------- | -------------------------------------------- | --------------------------------------------------- | +| `title` | ページタイトル (`og:title`) | `page.title` | +| `type` | ページタイプ (`og:type`) | article(記事ページ)<br>website(記事ページ以外) | +| `url` | ページURL (`og:url`) | `url` | +| `image` | ページ画像 (`og:image`) | コンテンツ内の全画像 | +| `author` | 記事の著者 (`og:article:author`) | `config.author` | +| `date` | 記事の公開時刻 (`og:article:published_time`) | ページの公開時刻 | +| `updated` | 記事の更新時刻 (`og:article:modified_time`) | ページの更新時刻 | +| `language` | 記事の言語 (`og:locale`) | `page.lang \|\| page.language \|\| config.language` | +| `site_name` | サイト名 (`og:site_name`) | `config.title` | +| `description` | ページの説明 (`og:description`) | ページの抜粋またはコンテンツの最初の200文字 | +| `twitter_card` | Twitter カードタイプ (`twitter:card`) | summary | +| `twitter_id` | Twitter ID (`twitter:creator`) | +| `twitter_site` | Twitter サイト (`twitter:site`) | +| `twitter_image` | Twitter 画像 (`twitter:image`) | +| `google_plus` | Google+ プロフィールリンク | +| `fb_admins` | Facebook 管理者ID | +| `fb_app_id` | Facebook アプリID | ### toc コンテンツ内の全ての見出しタグ (h1~h6) を解析し、目次を挿入します。 -``` js +```js <%- toc(str, [options]) %> ``` -オプション | 説明 | デフォルト ---- | --- | --- -`class` | クラス名 | `toc` -`class_item` (6.3.0以上) | アイテムのクラス名 | `${class}-item` -`class_link` (6.3.0以上) | リンクのクラス名 | `${class}-link` -`class_text` (6.3.0以上) | テキストのクラス名 | `${class}-text` -`class_child` (6.3.0以上) | 子のクラス名 | `${class}-child` -`class_number` (6.3.0以上) | 番号のクラス名 | `${class}-number` -`class_level` (6.3.0以上) | レベルのクラス名接頭辞 | `${class}-level` -`list_number` | リスト番号を表示するか? | true -`max_depth` | 生成される目次の最大見出し深さ | 6 -`min_depth` | 生成される目次の最小見出し深さ | 1 +| オプション | 説明 | デフォルト | +| -------------------------- | ------------------------------ | ----------------- | +| `class` | クラス名 | `toc` | +| `class_item` (6.3.0以上) | アイテムのクラス名 | `${class}-item` | +| `class_link` (6.3.0以上) | リンクのクラス名 | `${class}-link` | +| `class_text` (6.3.0以上) | テキストのクラス名 | `${class}-text` | +| `class_child` (6.3.0以上) | 子のクラス名 | `${class}-child` | +| `class_number` (6.3.0以上) | 番号のクラス名 | `${class}-number` | +| `class_level` (6.3.0以上) | レベルのクラス名接頭辞 | `${class}-level` | +| `list_number` | リスト番号を表示するか? | true | +| `max_depth` | 生成される目次の最大見出し深さ | 6 | +| `min_depth` | 生成される目次の最小見出し深さ | 1 | **例:** -``` js +```js <%- toc(page.content) %> ``` @@ -974,7 +974,7 @@ Google検索フォームを挿入します。 - https://github.com/hexojs/hexo/pull/4871 - https://github.com/hexojs/hexo-util/pull/269 - https://github.com/hexojs/hexo-renderer-markdown-it/pull/174 -{% endnote %} + {% endnote %} [色キーワード]: http://www.w3.org/TR/css3-color/#svg-color [Moment.js]: http://momentjs.com/ diff --git a/source/ja/docs/index.md b/source/ja/docs/index.md index c078a53a9f..4ad03eefa0 100644 --- a/source/ja/docs/index.md +++ b/source/ja/docs/index.md @@ -1,6 +1,7 @@ --- title: 概要 --- + Hexoのドキュメントへようこそ。利用中に問題に遭遇した場合は、[トラブルシューティング](troubleshooting.html)をご覧になるか、[GitHub](https://github.com/hexojs/hexo/issues)でIssueを報告したり、[Google Group](https://groups.google.com/group/hexo)でトピックを開始してください。 ## Hexoとは? @@ -62,7 +63,7 @@ Snapを使用してNode.jsをインストールした場合、ブログを[初 すべての要件がインストールされたら、npmでHexoをインストールできます: -``` bash +```bash $ npm install -g hexo-cli ``` @@ -70,7 +71,7 @@ $ npm install -g hexo-cli Node.jsに慣れたユーザーであれば、代わりに`hexo`パッケージをインストールして使用することを好むかもしれません。 -``` bash +```bash $ npm install hexo ``` @@ -79,11 +80,11 @@ $ npm install hexo 1. `npx hexo <command>` 2. Linuxユーザーは`node_modules/`フォルダの相対パスを設定できます: - ``` bash - echo 'PATH="$PATH:./node_modules/.bin"' >> ~/.profile - ``` +```bash +echo 'PATH="$PATH:./node_modules/.bin"' >> ~/.profile +``` - その後、`hexo <command>`を使用してHexoを実行します。 +その後、`hexo <command>`を使用してHexoを実行します。 ### 必要なNode.jsのバージョン @@ -93,15 +94,15 @@ Hexoの過去のバージョンへはバグ修正を提供していないこと 可能な限り、常にHexoの[最新バージョン](https://www.npmjs.com/package/hexo?activeTab=versions)と[推奨されるバージョン](#必要要件)のNode.jsをインストールすることを強く推奨します。 -Hexoバージョン | 最小 (Node.jsバージョン) | 未満 (Node.jsバージョン) ---- | --- | --- -7.0+ | 14.0.0 | latest -6.2+ | 12.13.0 | latest -6.0+ | 12.13.0 | 18.5.0 -5.0+ | 10.13.0 | 12.0.0 -4.1 - 4.2 | 8.10 | 10.0.0 -4.0 | 8.6 | 8.10.0 -3.3 - 3.9 | 6.9 | 8.0.0 -3.2 - 3.3 | 0.12 | unknown -3.0 - 3.1 | 0.10 or iojs | unknown -0.0.1 - 2.8 | 0.10 | unknown +| Hexoバージョン | 最小 (Node.jsバージョン) | 未満 (Node.jsバージョン) | +| -------------- | ------------------------ | ------------------------ | +| 7.0+ | 14.0.0 | latest | +| 6.2+ | 12.13.0 | latest | +| 6.0+ | 12.13.0 | 18.5.0 | +| 5.0+ | 10.13.0 | 12.0.0 | +| 4.1 - 4.2 | 8.10 | 10.0.0 | +| 4.0 | 8.6 | 8.10.0 | +| 3.3 - 3.9 | 6.9 | 8.0.0 | +| 3.2 - 3.3 | 0.12 | unknown | +| 3.0 - 3.1 | 0.10 or iojs | unknown | +| 0.0.1 - 2.8 | 0.10 | unknown | diff --git a/source/ja/docs/internationalization.md b/source/ja/docs/internationalization.md index c99a66200a..bd7c3bce93 100644 --- a/source/ja/docs/internationalization.md +++ b/source/ja/docs/internationalization.md @@ -1,9 +1,10 @@ --- title: 国際化 (i18n) --- + サイトを異なる言語で表示するために、国際化を使用できます。デフォルト言語は、`_config.yml` の `language` 設定を変更することで設定されます。複数の言語を設定し、デフォルト言語の順序を変更することもできます。 -``` yaml +```yaml language: zh-tw language: @@ -19,7 +20,7 @@ language: テンプレート内で翻訳された文字列を取得するために、`__` または `_p` ヘルパーを使用します。前者は通常の使用のためで、後者は複数形の文字列のためです。例えば: -``` yaml en.yml +```yaml en.yml index: title: Home add: Add @@ -29,7 +30,7 @@ index: other: %d videos ``` -``` js +```js <%= __('index.title') %> // Home @@ -41,13 +42,13 @@ index: Front Matterでページの言語を設定するか、`_config.yml` の `i18n_dir` 設定を変更して、Hexoによる自動検出を有効にできます。 -``` yaml +```yaml i18n_dir: :lang ``` `i18n_dir` 設定のデフォルト値は `:lang` です。これはHexoがURLの最初のセグメント内の言語を検出することを意味します。例えば: -``` plain +```plain /index.html => en /archives/index.html => en /zh-tw/index.html => zh-tw diff --git a/source/ja/docs/migration.md b/source/ja/docs/migration.md index 6c7b082010..d1bff73889 100644 --- a/source/ja/docs/migration.md +++ b/source/ja/docs/migration.md @@ -1,17 +1,18 @@ --- title: 移行 --- + ## RSS まず`hexo-migrator-rss`プラグインをインストールします。 -``` bash +```bash $ npm install hexo-migrator-rss --save ``` プラグインがインストールされたら、以下のコマンドを実行してRSSからすべての記事を移行します。`source`はファイルパスまたはURLです。 -``` bash +```bash $ hexo migrate rss <source> ``` @@ -21,7 +22,7 @@ Jekyllの`_posts`フォルダ内のすべてのファイルを`source/_posts`フ `_config.yml`の`new_post_name`設定を変更します: -``` yaml +```yaml new_post_name: :year-:month-:day-:title.md ``` @@ -31,7 +32,7 @@ Octopressの`source/_posts`フォルダ内のすべてのファイルを`source/ `_config.yml`の`new_post_name`設定を変更します: -``` yaml +```yaml new_post_name: :year-:month-:day-:title.md ``` @@ -39,7 +40,7 @@ new_post_name: :year-:month-:day-:title.md まず、`hexo-migrator-wordpress`プラグインをインストールします。 -``` bash +```bash $ npm install hexo-migrator-wordpress --save ``` @@ -47,7 +48,7 @@ WordPressダッシュボードで "Tools" → "Export" → "WordPress" に移動 次のコマンドを実行します: -``` bash +```bash $ hexo migrate wordpress <source> ``` diff --git a/source/ja/docs/one-command-deployment.md b/source/ja/docs/one-command-deployment.md index b31f2053f6..67cea1875e 100644 --- a/source/ja/docs/one-command-deployment.md +++ b/source/ja/docs/one-command-deployment.md @@ -21,10 +21,10 @@ deploy: ```yaml deploy: -- type: git - repo: -- type: heroku - repo: + - type: git + repo: + - type: heroku + repo: ``` 他のデプロイプラグインについては、[プラグイン](https://hexo.io/plugins/)リストを参照してください。 @@ -47,12 +47,12 @@ deploy: message: [message] ``` -オプション | 説明 | デフォルト ---- | --- | --- -`repo` | ターゲットリポジトリのURL | -`branch` | ブランチ名 | `gh-pages` (GitHub)<br>`coding-pages` (Coding.net)<br>`master` (その他) -`message` | コミットメッセージをカスタマイズ | `Site updated: {% raw %}{{ now('YYYY-MM-DD HH:mm:ss') }}{% endraw %}` -`token` | リポジトリの認証に使うオプションのトークン値。環境変数からトークンを読み込むには`$`をプレフィックスとして使用。 +| オプション | 説明 | デフォルト | +| ---------- | --------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- | +| `repo` | ターゲットリポジトリのURL | +| `branch` | ブランチ名 | `gh-pages` (GitHub)<br>`coding-pages` (Coding.net)<br>`master` (その他) | +| `message` | コミットメッセージをカスタマイズ | `Site updated: {% raw %}{{ now('YYYY-MM-DD HH:mm:ss') }}{% endraw %}` | +| `token` | リポジトリの認証に使うオプションのトークン値。環境変数からトークンを読み込むには`$`をプレフィックスとして使用。 | 3. サイトをデプロイします `hexo clean && hexo deploy`。 @@ -173,15 +173,15 @@ deploy: verbose: [true|false] ``` -| オプション | 説明 | デフォルト | -| ------------- | -------------------------------------| ---------- | -| `host` | リモートホストのアドレス | -| `user` | ユーザー名 | -| `pass` | パスワード | -| `remote` | リモートホストのルートディレクトリ | `/` | -| `port` | ポート | 21 | -| `clear` | アップロード前にリモートのファイルとディレクトリを全て削除 | false | -| `verbose` | 詳細なメッセージを表示 | false | +| オプション | 説明 | デフォルト | +| ---------- | ---------------------------------------------------------- | ---------- | +| `host` | リモートホストのアドレス | +| `user` | ユーザー名 | +| `pass` | パスワード | +| `remote` | リモートホストのルートディレクトリ | `/` | +| `port` | ポート | 21 | +| `clear` | アップロード前にリモートのファイルとディレクトリを全て削除 | false | +| `verbose` | 詳細なメッセージを表示 | false | ## SFTP @@ -206,7 +206,7 @@ deploy: agent: [path/to/agent/socket] ``` -| オプション | 説明 | デフォルト | +| オプション | 説明 | デフォルト | | ------------- | ------------------------------------------ | ---------------- | | `host` | リモートホストのアドレス | | `port` | ポート | 22 | @@ -279,8 +279,8 @@ $ hexo generate —deploy && bip deploy 2. 設定を変更します。 - ```yaml - deploy: # The root configuration block for all deployers +```yaml +deploy: # The root configuration block for all deployers - type: rss3 endpoint: https://hub.rss3.io privateKey: 47e18d6c386898b424025cd9db446f779ef24ad33a26c499c87bb3d9372540ba @@ -290,15 +290,15 @@ $ hexo generate —deploy && bip deploy api: key: d693df715d3631e489d6 secret: ee8b74626f12b61c1a4bde3b8c331ad390567c86ba779c9b18561ee92c1cbff0 - ``` - -| パラメータ | 説明 | -| ----------------- | ---------------------- | -| `endpoint` | RSS3ハブへのリンク | -| `privateKey` | あなたのプライベートキー、64バイト | -| `ipfs/deploy` | IPFSへのデプロイを実行するか? | -| `ipfs/gateway` | IPFS APIゲートウェイ | -| `ipfs/api/key` | IPFSゲートウェイ関連の認証コンテンツ | +``` + +| パラメータ | 説明 | +| ----------------- | ------------------------------------ | +| `endpoint` | RSS3ハブへのリンク | +| `privateKey` | あなたのプライベートキー、64バイト | +| `ipfs/deploy` | IPFSへのデプロイを実行するか? | +| `ipfs/gateway` | IPFS APIゲートウェイ | +| `ipfs/api/key` | IPFSゲートウェイ関連の認証コンテンツ | | `ipfs/api/secret` | IPFSゲートウェイ関連の認証コンテンツ | 3. 静的ファイルを生成します diff --git a/source/ja/docs/permalinks.md b/source/ja/docs/permalinks.md index faf1494a96..e266b558df 100644 --- a/source/ja/docs/permalinks.md +++ b/source/ja/docs/permalinks.md @@ -1,84 +1,85 @@ --- title: パーマリンク --- + `_config.yml`または各記事のFront Matterで、サイトのパーマリンクを設定できます。 ### 変数 Besides the following variables, you can use any attributes in the permalink except `:path` and `:permalink`. -変数 | 説明 ---- | --- -`:year` | 記事の公開年(4桁) -`:month` | 記事の公開月(2桁) -`:i_month` | 記事の公開月(先頭ゼロなし) -`:day` | 記事の公開日(2桁) -`:i_day` | 記事の公開日(先頭ゼロなし) -`:hour` | 記事の公開時(2桁) -`:minute` | 記事の公開分(2桁) -`:second` | 記事の公開秒(2桁) -`:title` | ファイル名("source/_posts/"フォルダーからの相対) -`:name` | ファイル名 -`:post_title` | 記事のタイトル -`:id` | 記事ID(_[キャッシュ削除](commands#clean)を跨いで永続しない_) -`:category` | カテゴリー。記事が未分類の場合、`default_category`の値を使用します。 -`:hash` | ファイル名(`:title`と同じ)と日付のSHA1ハッシュ(12桁の16進数) +| 変数 | 説明 | +| ------------- | -------------------------------------------------------------------- | +| `:year` | 記事の公開年(4桁) | +| `:month` | 記事の公開月(2桁) | +| `:i_month` | 記事の公開月(先頭ゼロなし) | +| `:day` | 記事の公開日(2桁) | +| `:i_day` | 記事の公開日(先頭ゼロなし) | +| `:hour` | 記事の公開時(2桁) | +| `:minute` | 記事の公開分(2桁) | +| `:second` | 記事の公開秒(2桁) | +| `:title` | ファイル名("source/\_posts/"フォルダーからの相対) | +| `:name` | ファイル名 | +| `:post_title` | 記事のタイトル | +| `:id` | 記事ID(_[キャッシュ削除](commands#clean)を跨いで永続しない_) | +| `:category` | カテゴリー。記事が未分類の場合、`default_category`の値を使用します。 | +| `:hash` | ファイル名(`:title`と同じ)と日付のSHA1ハッシュ(12桁の16進数) | パーマリンク内の各変数のデフォルト値を`permalink_defaults`設定を通じて定義することができます: -``` yaml +```yaml permalink_defaults: lang: en ``` ### 例 -``` yaml source/_posts/hello-world.md +```yaml source/_posts/hello-world.md title: Hello World date: 2013-07-14 17:01:34 categories: -- foo -- bar + - foo + - bar ``` -設定 | 結果 ---- | --- -`:year/:month/:day/:title/` | 2013/07/14/hello-world/ -`:year-:month-:day-:title.html` | 2013-07-14-hello-world.html -`:category/:title/` | foo/bar/hello-world/ -`:title-:hash/` | hello-world-a2c8ac003b43/ +| 設定 | 結果 | +| ------------------------------- | --------------------------- | +| `:year/:month/:day/:title/` | 2013/07/14/hello-world/ | +| `:year-:month-:day-:title.html` | 2013-07-14-hello-world.html | +| `:category/:title/` | foo/bar/hello-world/ | +| `:title-:hash/` | hello-world-a2c8ac003b43/ | -``` yaml source/_posts/lorem/hello-world.md +```yaml source/_posts/lorem/hello-world.md title: Hello World date: 2013-07-14 17:01:34 categories: -- foo -- bar + - foo + - bar ``` -設定 | 結果 ---- | --- -`:year/:month/:day/:title/` | 2013/07/14/lorem/hello-world/ -`:year/:month/:day/:name/` | 2013/07/14/hello-world/ +| 設定 | 結果 | +| --------------------------- | ----------------------------- | +| `:year/:month/:day/:title/` | 2013/07/14/lorem/hello-world/ | +| `:year/:month/:day/:name/` | 2013/07/14/hello-world/ | ### 多言語サポート 多言語サイトを作成するには、`new_post_name`および`permalink`設定を次のように変更します: -``` yaml +```yaml new_post_name: :lang/:title.md permalink: :lang/:title/ ``` 新しい記事を作成すると、記事は以下に保存されます: -``` bash +```bash $ hexo new "Hello World" --lang tw # => source/_posts/tw/Hello-World.md ``` そして、URLは以下になります: -``` plain +```plain http://localhost:4000/tw/hello-world/ ``` diff --git a/source/ja/docs/server.md b/source/ja/docs/server.md index b56116e4ed..06200c0dcc 100644 --- a/source/ja/docs/server.md +++ b/source/ja/docs/server.md @@ -1,23 +1,24 @@ --- title: サーバー --- + ## [hexo-server] Hexo 3のリリースとともに、サーバーはメインモジュールから分離されました。サーバーを使用開始するには、まず[hexo-server]をインストールする必要があります。 -``` bash +```bash $ npm install hexo-server --save ``` サーバーをインストールした後、以下のコマンドを実行してサーバーを起動します。デフォルトでは、あなたのウェブサイトは`http://localhost:4000`で実行されます。サーバーが実行中の場合、Hexoはファイルの変更を監視し、自動的に更新するので、手動でサーバーを再起動する必要はありません。 -``` bash +```bash $ hexo server ``` ポートを変更したい場合や`EADDRINUSE`エラーが発生している場合は、`-p`オプションを使用して異なるポートを設定します。 -``` bash +```bash $ hexo server -p 5000 ``` @@ -25,7 +26,7 @@ $ hexo server -p 5000 スタティックモードでは、`public`フォルダ内のファイルのみが提供され、ファイルの監視は無効になります。サーバーを起動する前に`hexo generate`を実行する必要があります。通常、本番環境で使用されます。 -``` bash +```bash $ hexo server -s ``` @@ -33,7 +34,7 @@ $ hexo server -s Hexoはデフォルトで`0.0.0.0`でサーバーを実行します。デフォルトのIPアドレスを上書きすることもできます。 -``` bash +```bash $ hexo server -i 192.168.1.1 ``` diff --git a/source/ja/docs/setup.md b/source/ja/docs/setup.md index 8e6ab048a5..0aa02180ee 100644 --- a/source/ja/docs/setup.md +++ b/source/ja/docs/setup.md @@ -4,7 +4,7 @@ title: セットアップ Hexoがインストールされたら、以下のコマンドを実行して対象の`<folder>`内でHexoを初期化します。 -``` bash +```bash $ hexo init <folder> $ cd <folder> $ npm install @@ -12,7 +12,7 @@ $ npm install 初期化されると、プロジェクトフォルダは次のようになります: -``` plain +```plain . ├── _config.yml ├── package.json @@ -23,7 +23,7 @@ $ npm install └── themes ``` -### _config.yml +### \_config.yml サイトの[設定](configuration.html)ファイルです。ほとんどの設定はここで行います。 @@ -31,7 +31,7 @@ $ npm install アプリケーションデータです。デフォルトで[EJS](https://ejs.co/)、[Stylus](http://learnboost.github.io/stylus/)、[Markdown](http://daringfireball.net/projects/markdown/)のレンダラーがインストールされています。必要に応じて、これらを後でアンインストールすることもできます。 -``` json package.json +```json package.json { "name": "hexo-site", "version": "0.0.0", diff --git a/source/ja/docs/syntax-highlight.md b/source/ja/docs/syntax-highlight.md index 62930f3091..2c1b4a552e 100644 --- a/source/ja/docs/syntax-highlight.md +++ b/source/ja/docs/syntax-highlight.md @@ -17,7 +17,7 @@ code snippet code snippet {% endcode %} -``` [language] [title] [url] [link text] [additional options] +```[language] [title] [url] [link text] [additional options] code snippet ``` ```` @@ -37,7 +37,7 @@ highlight: auto_detect: false line_number: true line_threshold: 0 - tab_replace: '' + tab_replace: "" exclude_languages: - example wrap: true @@ -47,7 +47,7 @@ prismjs: preprocess: true line_number: true line_threshold: 0 - tab_replace: '' + tab_replace: "" ``` v7.0.0以降: @@ -59,7 +59,7 @@ highlight: auto_detect: false line_number: true line_threshold: 0 - tab_replace: '' + tab_replace: "" exclude_languages: - example wrap: true @@ -68,7 +68,7 @@ prismjs: preprocess: true line_number: true line_threshold: 0 - tab_replace: '' + tab_replace: "" ``` 上記のYAMLはHexoのデフォルト設定です。 @@ -89,7 +89,7 @@ v7.0.0以降: ```yaml # _config.yml -syntax_highlighter: # empty +syntax_highlighter: # empty ``` `highlight.enable`と`prismjs.enable`が`false`(v7.0.0より前)か、`syntax_highlighter`が空(v7.0.0以降)の場合、コードブロックの出力HTMLは対応するレンダラーによって制御されます。例えば、[`marked.js`](https://github.com/markedjs/marked)(Hexoのデフォルトのmarkdownレンダラーである[`hexo-renderer-marked`](https://github.com/hexojs/hexo-renderer-marked)に使用されています)は、`<code>`の`class`に言語コードを追加します: @@ -119,7 +119,7 @@ highlight: auto_detect: false line_number: true line_threshold: 0 - tab_replace: ' ' + tab_replace: " " exclude_languages: - example wrap: true @@ -137,7 +137,7 @@ highlight: auto_detect: false line_number: true line_threshold: 0 - tab_replace: ' ' + tab_replace: " " exclude_languages: - example wrap: true @@ -166,18 +166,18 @@ Hexoは、出力を`<figure>`と`<table>`でラップし行番号を追加しま ```html <figure class="highlight yaml"> -<table> -<tbody> -<tr> - <td class="gutter"> - <pre><span class="line">1</span><br></pre> - </td> - <td class="code"> - <pre><span class="line"><span class="attr">hello:</span><span class="string">hexo</span></span><br></pre> - </td> -</tr> -</tbody> -</table> + <table> + <tbody> + <tr> + <td class="gutter"> + <pre><span class="line">1</span><br></pre> + </td> + <td class="code"> + <pre><span class="line"><span class="attr">hello:</span><span class="string">hexo</span></span><br></pre> + </td> + </tr> + </tbody> + </table> </figure> ``` @@ -238,7 +238,7 @@ prismjs: preprocess: true line_number: true line_threshold: 0 - tab_replace: '' + tab_replace: "" ``` v7.0.0以降: @@ -250,7 +250,7 @@ prismjs: preprocess: true line_number: true line_threshold: 0 - tab_replace: '' + tab_replace: "" ``` Prismjsはデフォルトで無効になっています。prismjsを有効にする前に、v7.0.0より前では`highlight.enable`を`false`に設定するか、v7.0.0以降では`syntax_highlighter`を`prismjs`に設定する必要があります。 diff --git a/source/ja/docs/tag-plugins.md b/source/ja/docs/tag-plugins.md index 4e1e659bd8..f73a8d96a1 100644 --- a/source/ja/docs/tag-plugins.md +++ b/source/ja/docs/tag-plugins.md @@ -1,6 +1,7 @@ --- title: タグプラグイン --- + タグプラグインは記事に付与するタグとは異なります。これらはOctopressから移植されました。特定のコンテンツを記事に素早く追加するのに便利です。 記事は任意のフォーマットで書くことができますが、何れの場合もタグプラグインは利用可能です。構文には変わりはありません。 @@ -83,14 +84,14 @@ code snippet 追加オプションは `option:value` 形式で指定します。例: `line_number:false first_line:5`。 -追加オプション | 説明 | デフォルト ---- | --- | --- -`line_number` | 行番号を表示 | `true` -`line_threshold` | コードブロックの行数がこの閾値を超える場合にのみ行番号を表示。 | `0` | -`highlight` | コードのハイライトを有効にする | `true` -`first_line` | 最初の行番号を指定 | `1` -`mark` | コンマ区切りで指定された行をハイライト。範囲指定にはハイフンを使用<br>例: `mark:1,4-7,10` は行1、4から7、10をマークします。 | -`wrap` | コードブロックを[`<table>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table)でラップ | `true` +| 追加オプション | 説明 | デフォルト | +| ---------------- | --------------------------------------------------------------------------------------------------------------------------- | ---------- | +| `line_number` | 行番号を表示 | `true` | +| `line_threshold` | コードブロックの行数がこの閾値を超える場合にのみ行番号を表示。 | `0` | +| `highlight` | コードのハイライトを有効にする | `true` | +| `first_line` | 最初の行番号を指定 | `1` | +| `mark` | コンマ区切りで指定された行をハイライト。範囲指定にはハイフンを使用<br>例: `mark:1,4-7,10` は行1、4から7、10をマークします。 | +| `wrap` | コードブロックを[`<table>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table)でラップ | `true` | ### 例 @@ -140,7 +141,7 @@ _.compact([0, 1, false, 2, '', 3]); ``` {% codeblock _.compact http://underscorejs.org/#compact Underscore.js %} -_.compact([0, 1, false, 2, '', 3]); +\_.compact([0, 1, false, 2, '', 3]); => [1, 2, 3] {% endcodeblock %} @@ -149,9 +150,9 @@ _.compact([0, 1, false, 2, '', 3]); これはコードブロックの使用と同じですが、ブロックを区切るために3つのバックティックを使用します。 {% raw %} -``` [language] [title] [url] [link text] +`` [language] [title] [url] [link text] code snippet -``` +`` {% endraw %} ## プルクオート @@ -368,32 +369,32 @@ _hexo-renderer-marked 3.1.0+は、オプションで画像の記事パスを自 `{% asset_img foo.jpg %}` -``` html -<img src="/2020/01/02/hello/foo.jpg"> +```html +<img src="/2020/01/02/hello/foo.jpg" /> ``` **カスタムクラス** `{% asset_img post-image foo.jpg %}` -``` html -<img src="/2020/01/02/hello/foo.jpg" class="post-image"> +```html +<img src="/2020/01/02/hello/foo.jpg" class="post-image" /> ``` **サイズを指定** `{% asset_img foo.jpg 500 400 %}` -``` html -<img src="/2020/01/02/hello/foo.jpg" width="500" height="400"> +```html +<img src="/2020/01/02/hello/foo.jpg" width="500" height="400" /> ``` **タイトル & Alt** `{% asset_img foo.jpg "lorem ipsum'dolor'" %}` -``` html -<img src="/2020/01/02/hello/foo.jpg" title="lorem ipsum" alt="dolor"> +```html +<img src="/2020/01/02/hello/foo.jpg" title="lorem ipsum" alt="dolor" /> ``` ## URL @@ -408,23 +409,23 @@ _hexo-renderer-marked 3.1.0+は、オプションで画像の記事パスを自 **例:** -``` yml +```yml _config.yml root: /blog/ # 例 ``` -``` +``` {% url_for blog index.html %} ``` -``` html +```html <a href="/blog/index.html">blog</a> ``` 相対リンク指定はデフォルトで`relative_link`オプションに従います。 例えば、記事/ページのパスが'/foo/bar/index.html'の場合 -``` yml +```yml _config.yml relative_link: true ``` @@ -433,7 +434,7 @@ relative_link: true {% url_for blog index.html %} ``` -``` html +```html <a href="../../index.html">blog</a> ``` @@ -443,7 +444,7 @@ relative_link: true {% url_for blog index.html false %} ``` -``` html +```html <a href="/index.html">blog</a> ``` @@ -457,7 +458,7 @@ relative_link: true **例:** -``` yml +```yml _config.yml url: https://example.com/blog # example ``` @@ -466,7 +467,7 @@ url: https://example.com/blog # example {% full_url_for index /a/path %} ``` -``` html +```html <a href="https://example.com/blog/a/path">index</a> ``` diff --git a/source/ja/docs/templates.md b/source/ja/docs/templates.md index 220bfd2715..5534b2613e 100644 --- a/source/ja/docs/templates.md +++ b/source/ja/docs/templates.md @@ -1,38 +1,43 @@ --- title: テンプレート --- + テンプレートは、ウェブサイトの外観の構造を定義します。つまり、各ページがどのように表示されるべきか記述します。下記の表は、利用可能な各ページに対応するテンプレートを示しています。最低限、テーマには`index`テンプレートが必要です。 -テンプレート | ページ | フォールバック ---- | --- | --- -`index` | ホームページ | -`post` | 記事 | `index` -`page` | ページ | `index` -`archive` | アーカイブ | `index` -`category` | カテゴリーアーカイブ | `archive` -`tag` | タグアーカイブ | `archive` +| テンプレート | ページ | フォールバック | +| ------------ | -------------------- | -------------- | +| `index` | ホームページ | +| `post` | 記事 | `index` | +| `page` | ページ | `index` | +| `archive` | アーカイブ | `index` | +| `category` | カテゴリーアーカイブ | `archive` | +| `tag` | タグアーカイブ | `archive` | ## レイアウト ページが似通った構造を持つ場合(例えば、二つのテンプレートがヘッダーとフッターを持つ場合)、これらの構造上の類似性を宣言するために`layout`を使用できます。すべてのレイアウトファイルには、該当するテンプレートの内容を表示するための`body`変数が必要です。例えば: -``` html index.ejs +```html index.ejs index ``` -``` html layout.ejs -<!DOCTYPE html> +```html layout.ejs +<!doctype html> <html> - <body><%- body %></body> + <body> + <%- body %> + </body> </html> ``` は次のようになります: -``` html -<!DOCTYPE html> +```html +<!doctype html> <html> - <body>index</body> + <body> + index + </body> </html> ``` @@ -42,18 +47,18 @@ index パーシャルを利用し、テンプレート間でコンポーネントを共有できます。典型的な例には、ヘッダー、フッター、サイドバーなどがあります。メンテナンスを便利にするために、パーシャルを別のファイルに置くことができます。例えば: -``` html partial/header.ejs +```html partial/header.ejs <h1 id="logo"><%= config.title %></h1> ``` -``` html index.ejs +```html index.ejs <%- partial('partial/header') %> <div id="content">Home page</div> ``` は次のようになります: -``` html +```html <h1 id="logo">My Site</h1> <div id="content">Home page</div> ``` @@ -62,18 +67,18 @@ index テンプレート内でローカル変数を定義し、他のテンプレートから利用できます。 -``` html partial/header.ejs +```html partial/header.ejs <h1 id="logo"><%= title %></h1> ``` -``` html index.ejs +```html index.ejs <%- partial('partial/header', {title: 'Hello World'}) %> <div id="content">Home page</div> ``` は次のようになります: -``` html +```html <h1 id="logo">Hello World</h1> <div id="content">Home page</div> ``` @@ -86,7 +91,7 @@ index Fragment cachingは、テンプレート間で変わらないと予想される、ヘッダー、フッター、サイドバー、その他の静的コンテンツに最適です。例えば: -``` js +```js <%- fragment_cache('header', function(){ return '<header></header>'; }); @@ -94,7 +99,7 @@ Fragment cachingは、テンプレート間で変わらないと予想される パーシャルを使用する方が簡単かもしれません: -``` js +```js <%- partial('header', {}, {cache: true}); ``` diff --git a/source/ja/docs/themes.md b/source/ja/docs/themes.md index 1377cfc34a..82f8ce2315 100644 --- a/source/ja/docs/themes.md +++ b/source/ja/docs/themes.md @@ -71,7 +71,7 @@ Hexoは、すべてのレンダリング可能なファイルを処理し`public - one_column ``` -5. スクリーンショット(テーマと同じ名前)を`source/themes/screenshots`に追加します。800*500pxのPNGでなければなりません。 +5. スクリーンショット(テーマと同じ名前)を`source/themes/screenshots`に追加します。800\*500pxのPNGでなければなりません。 6. ブランチをプッシュします。 7. プルリクエストを作成し、変更を説明します。 diff --git a/source/ja/docs/troubleshooting.md b/source/ja/docs/troubleshooting.md index de8cbe0dea..c6971b4247 100644 --- a/source/ja/docs/troubleshooting.md +++ b/source/ja/docs/troubleshooting.md @@ -1,18 +1,19 @@ --- title: トラブルシューティング --- + Hexoの使用中に頻繁に遭遇する問題に対する解決策のリストをここに示します。このページで問題が解決しない場合は、[GitHub](https://github.com/hexojs/hexo/issues)や[Google Group](https://groups.google.com/group/hexo)で検索してみてください。 ## YAML解析エラー -``` plain +```plain JS-YAML: incomplete explicit mapping pair; a key node is missed at line 18, column 29: last_updated: Last updated: %s ``` 文字列にコロンが含まれている場合は、引用符で囲みます。 -``` plain +```plain JS-YAML: bad indentation of a mapping entry at line 18, column 31: last_updated:"Last updated: %s" ``` @@ -23,13 +24,13 @@ JS-YAML: bad indentation of a mapping entry at line 18, column 31: ## EMFILEエラー -``` plain +```plain Error: EMFILE, too many open files ``` Node.jsはノンブロッキングI/Oを持っていますが、システムによって同時に実行できる同期I/Oの最大数には制限があります。大量のファイルを生成しようとするときにEMFILEエラーに遭遇することがあります。以下のコマンドを実行して、許可される同期I/O操作の数を増やしてみてください。 -``` bash +```bash $ ulimit -n 10000 ``` @@ -37,7 +38,7 @@ $ ulimit -n 10000 次のエラーに遭遇した場合: -``` bash +```bash $ ulimit -n 10000 ulimit: open files: cannot modify limit: Operation not permitted ``` @@ -48,23 +49,23 @@ ulimit: open files: cannot modify limit: Operation not permitted 1. "/etc/security/limits.conf"に以下の行を追加します: - ``` - * - nofile 10000 +``` +* - nofile 10000 - # '*'はすべてのユーザーに適用され、'-'はソフトとハードの両方の制限を設定します - ``` +# '*'はすべてのユーザーに適用され、'-'はソフトとハードの両方の制限を設定します +``` - * 上記の設定が適用されない場合があるため、"/etc/pam.d/login"と"/etc/pam.d/lightdm"に以下の行が含まれていることを確認してください。(これらのファイルが存在しない場合はこのステップを無視してください) +- 上記の設定が適用されない場合があるため、"/etc/pam.d/login"と"/etc/pam.d/lightdm"に以下の行が含まれていることを確認してください。(これらのファイルが存在しない場合はこのステップを無視してください) - ``` - session required pam_limits.so - ``` +``` +session required pam_limits.so +``` 2. [systemdベースのディストリビューション](https://en.wikipedia.org/wiki/Systemd#Adoption)を使用している場合、systemdは"limits.conf"を上書きする可能性があります。systemdで制限を設定するには、"/etc/systemd/system.conf"と"/etc/systemd/user.conf"に以下の行を追加します: - ``` - DefaultLimitNOFILE=10000 - ``` +``` +DefaultLimitNOFILE=10000 +``` 3. 再起動 @@ -88,7 +89,7 @@ FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory ### RPC失敗 -``` plain +```plain error: RPC failed; result=22, HTTP code = 403 fatal: 'username.github.io' does not appear to be a git repository @@ -113,19 +114,19 @@ fatal: 'username.github.io' does not appear to be a git repository ## サーバーの問題 -``` plain +```plain Error: listen EADDRINUSE ``` 同時に2つのHexoサーバーを起動したか、別のアプリケーションが同じポートを使用している可能性があります。`port`設定を変更するか、`-p`フラグを使用してHexoサーバーを起動してみてください。 -``` bash +```bash $ hexo server -p 5000 ``` ## プラグインのインストール問題 -``` plain +```plain npm ERR! node-waf configure build ``` @@ -160,7 +161,7 @@ Hexoはデータモデルに[Warehouse]を使用しています。これは配 一部のデータは更新されず、新しく生成されたファイルが前のバージョンと同一になることがあります。キャッシュをクリーンして再試行してください。 -``` bash +```bash $ hexo clean ``` @@ -178,7 +179,7 @@ $ hexo clean ## コンテンツのエスケープ -Hexoは記事をレンダリングするために[Nunjucks]を使用しています(以前のバージョンでは、同様の構文を共有する[Swig]が使用されていました)。`{{ }}`または`{% %}`で囲まれたコンテンツはパースの際に問題を引き起こす可能性があります。[`raw`](tag-plugins#Raw)タグプラグイン、単一のバックティック```` `{{ }}` ````、またはトリプルバックティックでパースをスキップできます。 +Hexoは記事をレンダリングするために[Nunjucks]を使用しています(以前のバージョンでは、同様の構文を共有する[Swig]が使用されていました)。`{{ }}`または`{% %}`で囲まれたコンテンツはパースの際に問題を引き起こす可能性があります。[`raw`](tag-plugins#Raw)タグプラグイン、単一のバックティック`` `{{ }}` ``、またはトリプルバックティックでパースをスキップできます。 または、レンダラーのオプション(サポートされている場合)、[API](../api/renderer#Nunjucksタグを無効にする)、または[Front Matter](front-matter)を通じてNunjucksタグを無効にすることもできます。 ``` @@ -219,7 +220,7 @@ Error: watch /path/to/hexo/theme/ EMPERM 残念ながら、WSLは現在ファイルシステムウォッチャをサポートしていません。そのため、hexoサーバーのライブ更新機能は現在利用できません。ファイルを最初に生成してから、静的サーバーとして実行することにより、WSL環境からサーバーを実行することは可能です: -``` sh +```sh $ hexo generate $ hexo server -s ``` @@ -236,9 +237,12 @@ Template render error: (unknown path) ``` 考えられる原因: + - ファイルに認識できない単語が含まれていることがあります。例えば、見えないゼロ幅文字などです。 - [タグプラグイン](tag-plugins)の誤用または制限。 - * コンテンツが`{% endplugin_name %}`で閉じられていないブロックスタイルのタグプラグイン + + - コンテンツが`{% endplugin_name %}`で閉じられていないブロックスタイルのタグプラグイン + ``` # 誤り {% codeblock %} @@ -254,7 +258,9 @@ Template render error: (unknown path) fn() {% endcodeblock %} ``` - * タグプラグインでNunjucksのような構文を含んでいる場合、例えば[`{% raw %}{#{% endraw %}`](https://mozilla.github.io/nunjucks/templating.html#comments)。この例の回避策は、[トリプルバックティック](tag-plugins#バックティックコードブロック)を代わりに使用することです。[コンテンツのエスケープ](troubleshooting#コンテンツのエスケープ)セクションに詳細があります。 + + - タグプラグインでNunjucksのような構文を含んでいる場合、例えば[`{% raw %}{#{% endraw %}`](https://mozilla.github.io/nunjucks/templating.html#comments)。この例の回避策は、[トリプルバックティック](tag-plugins#バックティックコードブロック)を代わりに使用することです。[コンテンツのエスケープ](troubleshooting#コンテンツのエスケープ)セクションに詳細があります。 + ``` {% codeblock lang:bash %} Size of array is ${#ARRAY} @@ -275,10 +281,13 @@ YAMLException: Specified list of YAML types (or a single Type object) contains a ```sh $ npm install js-yaml@latest ``` + または、`yarn`を使用している場合は + ```sh $ yarn add js-yaml@latest ``` + を実行してください。 [Warehouse]: https://github.com/hexojs/warehouse diff --git a/source/ja/docs/variables.md b/source/ja/docs/variables.md index cedcf88072..7c029ddc4d 100644 --- a/source/ja/docs/variables.md +++ b/source/ja/docs/variables.md @@ -4,15 +4,15 @@ title: 変数 ### グローバル変数 -変数 | 説明 | タイプ ---- | --- | --- -`site` | サイト全体の情報。 | `object`; [サイト変数]を参照 -`page` | ページ固有の情報とFront Matterで設定されたカスタム変数。 | `object`; [ページ変数]を参照 -`config` | サイト設定。 | `object` (あなたのサイトの_configファイル) -`theme` | テーマ設定。サイト設定から継承。 | `object` (あなたのテーマの_configファイル) -`path` | 現在のページのパス | `string` -`url` | 現在のページの完全なURL | `string` -`env` | 環境変数 | ??? +| 変数 | 説明 | タイプ | +| -------- | -------------------------------------------------------- | ------------------------------------------- | +| `site` | サイト全体の情報。 | `object`; [サイト変数]を参照 | +| `page` | ページ固有の情報とFront Matterで設定されたカスタム変数。 | `object`; [ページ変数]を参照 | +| `config` | サイト設定。 | `object` (あなたのサイトの\_configファイル) | +| `theme` | テーマ設定。サイト設定から継承。 | `object` (あなたのテーマの\_configファイル) | +| `path` | 現在のページのパス | `string` | +| `url` | 現在のページの完全なURL | `string` | +| `env` | 環境変数 | ??? | {% note warn %} LodashはHexo 5.0.0でグローバル変数から削除されました。[You-Dont-Need-Lodash-Underscore](https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore)が移行に役立つかもしれません。 @@ -20,79 +20,79 @@ LodashはHexo 5.0.0でグローバル変数から削除されました。[You-Do ### サイト変数 -変数 | 説明 | タイプ ---- | --- | --- -`site.posts` | 全ての記事 | `array` of `post` objects -`site.pages` | 全てのページ | `array` of `page` objects -`site.categories` | 全てのカテゴリ | `array` of ??? -`site.tags` | 全てのタグ | `array` of ??? +| 変数 | 説明 | タイプ | +| ----------------- | -------------- | ------------------------- | +| `site.posts` | 全ての記事 | `array` of `post` objects | +| `site.pages` | 全てのページ | `array` of `page` objects | +| `site.categories` | 全てのカテゴリ | `array` of ??? | +| `site.tags` | 全てのタグ | `array` of ??? | ### ページ変数 **ページ (`page`)** -変数 | 説明 | タイプ ---- | --- | --- -`page.title` | ページのタイトル | `string` -`page.date` | ページの作成日 | [Moment.js] オブジェクト -`page.updated` | ページの最終更新日 | [Moment.js] オブジェクト -`page.comments` | コメントが有効か? | `boolean` -`page.layout` | レイアウト名 | `string` -`page.content` | ページの完全な処理結果 | `string` -`page.excerpt` | ページの抜粋 | `string` -`page.more` | 抜粋を除いたページの内容 | `string` -`page.source` | ソースファイルのパス | `string` -`page.full_source` | ソースファイルの完全なパス | `string` -`page.path` | ページのURL(ルートURLを除く)。テーマでは通常 `url_for(page.path)` を使用します。 | `string` -`page.permalink` | ページの完全な(エンコードされた)URL | `string` -`page.prev` | 前のページ、最初のページの場合は `null` | ??? -`page.next` | 次のページ、最後のページの場合は `null` | ??? -`page.raw` | ページのローデータ | ??? -`page.photos` | ページの写真(ギャラリーページで使用) | array of ??? -`page.link` | ページの外部リンク(リンクページで使用) | `string` +| 変数 | 説明 | タイプ | +| ------------------ | ---------------------------------------------------------------------------------- | ------------------------ | +| `page.title` | ページのタイトル | `string` | +| `page.date` | ページの作成日 | [Moment.js] オブジェクト | +| `page.updated` | ページの最終更新日 | [Moment.js] オブジェクト | +| `page.comments` | コメントが有効か? | `boolean` | +| `page.layout` | レイアウト名 | `string` | +| `page.content` | ページの完全な処理結果 | `string` | +| `page.excerpt` | ページの抜粋 | `string` | +| `page.more` | 抜粋を除いたページの内容 | `string` | +| `page.source` | ソースファイルのパス | `string` | +| `page.full_source` | ソースファイルの完全なパス | `string` | +| `page.path` | ページのURL(ルートURLを除く)。テーマでは通常 `url_for(page.path)` を使用します。 | `string` | +| `page.permalink` | ページの完全な(エンコードされた)URL | `string` | +| `page.prev` | 前のページ、最初のページの場合は `null` | ??? | +| `page.next` | 次のページ、最後のページの場合は `null` | ??? | +| `page.raw` | ページのローデータ | ??? | +| `page.photos` | ページの写真(ギャラリーページで使用) | array of ??? | +| `page.link` | ページの外部リンク(リンクページで使用) | `string` | **記事 (`post`):** `page` レイアウトと同じですが、以下の変数が追加されます。 -変数 | 説明 | タイプ ---- | --- | --- -`page.published` | 記事が下書きでない場合はTrue | `boolean` -`page.categories` | 記事の全カテゴリ | `array` of ??? -`page.tags` | 記事の全タグ | `array` of ??? +| 変数 | 説明 | タイプ | +| ----------------- | ---------------------------- | -------------- | +| `page.published` | 記事が下書きでない場合はTrue | `boolean` | +| `page.categories` | 記事の全カテゴリ | `array` of ??? | +| `page.tags` | 記事の全タグ | `array` of ??? | **ホーム (`index`)** -変数 | 説明 | タイプ ---- | --- | --- -`page.per_page` | 1ページあたりの記事表示数 | `number` -`page.total` | ページの総数 | `number` -`page.current` | 現在のページ番号 | `number` -`page.current_url` | 現在のページのURL | `string` -`page.posts` | このページの記事 ([データモデル](https://hexojs.github.io/warehouse/)) | `object` -`page.prev` | 前のページ番号。現在のページが最初の場合は `0`。 | `number` -`page.prev_link` | 前のページのURL。現在のページが最初の場合は `''`。 | `string` -`page.next` | 次のページ番号。現在のページが最後の場合は `0`。 | `number` -`page.next_link` | 次のページのURL。現在のページが最後の場合は `''`。 | `string` -`page.path` | 現在のページのURL(ルートURLを除く)。テーマでは通常 `url_for(page.path)` を使用します。 | `string` +| 変数 | 説明 | タイプ | +| ------------------ | ---------------------------------------------------------------------------------------- | -------- | +| `page.per_page` | 1ページあたりの記事表示数 | `number` | +| `page.total` | ページの総数 | `number` | +| `page.current` | 現在のページ番号 | `number` | +| `page.current_url` | 現在のページのURL | `string` | +| `page.posts` | このページの記事 ([データモデル](https://hexojs.github.io/warehouse/)) | `object` | +| `page.prev` | 前のページ番号。現在のページが最初の場合は `0`。 | `number` | +| `page.prev_link` | 前のページのURL。現在のページが最初の場合は `''`。 | `string` | +| `page.next` | 次のページ番号。現在のページが最後の場合は `0`。 | `number` | +| `page.next_link` | 次のページのURL。現在のページが最後の場合は `''`。 | `string` | +| `page.path` | 現在のページのURL(ルートURLを除く)。テーマでは通常 `url_for(page.path)` を使用します。 | `string` | **アーカイブ (`archive`):** `index` レイアウトと同じですが、以下の変数が追加されます。 -変数 | 説明 | タイプ ---- | --- | --- -`page.archive` | 固定値 `true` | `boolean` -`page.year` | アーカイブの年(4桁) | `number` -`page.month` | アーカイブの月(先頭ゼロなしの2桁) | `number` +| 変数 | 説明 | タイプ | +| -------------- | ----------------------------------- | --------- | +| `page.archive` | 固定値 `true` | `boolean` | +| `page.year` | アーカイブの年(4桁) | `number` | +| `page.month` | アーカイブの月(先頭ゼロなしの2桁) | `number` | **カテゴリ (`category`):** `index` レイアウトと同じですが、以下の変数が追加されます。 -変数 | 説明 | タイプ ---- | --- | --- -`page.category` | カテゴリ名 | `string` +| 変数 | 説明 | タイプ | +| --------------- | ---------- | -------- | +| `page.category` | カテゴリ名 | `string` | **タグ (`tag`):** `index` レイアウトと同じですが、以下の変数が追加されます。 -変数 | 説明 | タイプ ---- | --- | --- -`page.tag` | タグ名 | `string` +| 変数 | 説明 | タイプ | +| ---------- | ------ | -------- | +| `page.tag` | タグ名 | `string` | [Moment.js]: http://momentjs.com/ [サイト変数]: #サイト変数 diff --git a/source/ja/docs/writing.md b/source/ja/docs/writing.md index 2ca26f181f..7ed20dbf9c 100644 --- a/source/ja/docs/writing.md +++ b/source/ja/docs/writing.md @@ -4,7 +4,7 @@ title: 執筆 新しい記事やページを作成するには、次のコマンドを実行します: -``` bash +```bash $ hexo new [layout] <title> ``` @@ -14,11 +14,11 @@ $ hexo new [layout] <title> Hexoには `post`、`page`、`draft` の3つのデフォルトレイアウトがあります。それぞれのレイアウトより作成されたファイルは異なるパスに保存されます。新しく作成された記事は`source/_posts`フォルダに保存されます。 -レイアウト | パス ---- | --- -`post` | `source/_posts` -`page` | `source` -`draft` | `source/_drafts` +| レイアウト | パス | +| ---------- | ---------------- | +| `post` | `source/_posts` | +| `page` | `source` | +| `draft` | `source/_drafts` | {% note tip レイアウトの無効化 %} テーマで処理されない記事やページを作成する場合、Front Matterに`layout: false`を設定してください。詳細は[このセクション](front-matter#レイアウト)を参照してください。 @@ -28,20 +28,20 @@ Hexoには `post`、`page`、`draft` の3つのデフォルトレイアウトが デフォルトでは、Hexoは記事タイトルをファイル名として使用します。`_config.yml`の`new_post_name`設定を編集することで、デフォルトのファイル名を変更できます。例えば、`:year-:month-:day-:title.md`は記事作成日をファイル名の冒頭に付与します。以下のプレースホルダを使用できます: -プレースホルダ | 説明 ---- | --- -`:title` | 記事タイトル(小文字、スペースはハイフンに置き換えられます) -`:year` | 作成年(例: `2015`) -`:month` | 作成月(先頭のゼロ付き)、例: `04` -`:i_month` | 作成月(先頭のゼロなし)、例: `4` -`:day` | 作成日(先頭のゼロ付き)、例: `07` -`:i_day` | 作成日(先頭のゼロなし)、例: `7` +| プレースホルダ | 説明 | +| -------------- | ------------------------------------------------------------ | +| `:title` | 記事タイトル(小文字、スペースはハイフンに置き換えられます) | +| `:year` | 作成年(例: `2015`) | +| `:month` | 作成月(先頭のゼロ付き)、例: `04` | +| `:i_month` | 作成月(先頭のゼロなし)、例: `4` | +| `:day` | 作成日(先頭のゼロ付き)、例: `07` | +| `:i_day` | 作成日(先頭のゼロなし)、例: `7` | ## 下書き 以前に、Hexoの特別なレイアウトとして`draft`について触れました。このレイアウトで初期化された記事は`source/_drafts`フォルダに保存されます。`publish`コマンドを使用して、下書きを`source/_posts`フォルダに移動できます。`publish`は`new`コマンドと同様の方法で機能します。 -``` bash +```bash $ hexo publish [layout] <title> ``` @@ -51,17 +51,17 @@ $ hexo publish [layout] <title> 記事を作成するとき、Hexoは`scaffolds`フォルダ内の対応するファイルに基づいてファイルを構築します。例えば: -``` bash +```bash $ hexo new photo "My Gallery" ``` このコマンドを実行すると、Hexoは`scaffolds`フォルダ内の`photo.md`を探して、それに基づいて記事を構築します。スキャフォールド内で利用可能なプレースホルダは以下の通りです: -プレースホルダ | 説明 ---- | --- -`layout` | レイアウト -`title` | タイトル -`date` | ファイル作成日 +| プレースホルダ | 説明 | +| -------------- | -------------- | +| `layout` | レイアウト | +| `title` | タイトル | +| `date` | ファイル作成日 | ## サポートされるフォーマット diff --git a/source/ko/api/box.md b/source/ko/api/box.md index 379f6e1bd0..3eb6fd6569 100644 --- a/source/ko/api/box.md +++ b/source/ko/api/box.md @@ -1,18 +1,19 @@ --- title: Box --- + Box는 특정 폴더 안의 파일들을 처리하기 위해 사용되는 컨테이너 입니다. Hexo는 `hexo.source`와 `hexo.theme` 두 가지 종류의 Box를 사용합니다: `hexo.source`는 `source` 폴더를 처리할 때 사용되고 `hexo.theme`는 `theme` 폴더를 처리할 때 사용됩니다. ## 파일 불러오기 Box는 `process`와 `watch` 두 가지 종류의 메소드를 지원합니다. `process`는 폴더 안의 모든 파일을 불러옵니다. `watch`도 동일한 동작을 수행하지만 파일이 변경되는 것을 감지(watching)합니다. -``` js -box.process().then(function(){ +```js +box.process().then(function () { // ... }); -box.watch().then(function(){ +box.watch().then(function () { // You can call box.unwatch() later to stop watching. }); ``` @@ -21,7 +22,7 @@ box.watch().then(function(){ Box는 다양한 방법을 통해 경로를 매칭시킵니다. 당신은 함수 또는 Express-style pattern string을 통해 정규 표현식을 사용할 수 있습니다. 아래는 예시입니다: -``` plain +```plain posts/:id => posts/89 posts/*path => posts/2015/title ``` @@ -32,30 +33,30 @@ posts/*path => posts/2015/title 프로세서는 Box의 핵심이 되는 요소이며, 파일을 처리할 때 사용됩니다. 경로 매칭을 사용하여 프로세서가 어떤 프로세스를 처리해야 하는지 제한할 수 있습니다. 새로운 프로세서는 `addProcessor` 메소드를 통해 등록할 수 있습니다. -``` js -box.addProcessor('posts/:id', function(file){ +```js +box.addProcessor("posts/:id", function (file) { // }); ``` Box는 매칭된 파일의 콘텐츠를 프로세서로 넘겨줍니다. 이 정보는 callback의 `file` 인자로부터 직접 읽을 수 있습니다. -속성 | 설명 ---- | --- -`source` | 파일의 전체 경로 -`path` | 파일의 box에 대한 상대 경로 -`type` | 파일의 형식. `create`, `update`, `skip`, `delete` 네 가지 값을 가질 수 있습니다. -`params` | 경로 매칭으로부터 얻은 정보. +| 속성 | 설명 | +| -------- | -------------------------------------------------------------------------------- | +| `source` | 파일의 전체 경로 | +| `path` | 파일의 box에 대한 상대 경로 | +| `type` | 파일의 형식. `create`, `update`, `skip`, `delete` 네 가지 값을 가질 수 있습니다. | +| `params` | 경로 매칭으로부터 얻은 정보. | Box는 개발자의 부담을 덜어주기 위해 file IO에 대한 몇 가지 메소드를 제공합니다. -메소드 | 설명 ---- | --- -`read` | 파일을 읽습니다 -`readSync` | 파일을 동기적으로 읽습니다 -`stat` | 파일의 상태를 읽습니다 -`statSync` | 파일의 상태를 동기적으로 읽습니다 -`render` | 파일을 생성합니다 -`renderSync` | 파일을 동기적으로 생성합니다 +| 메소드 | 설명 | +| ------------ | --------------------------------- | +| `read` | 파일을 읽습니다 | +| `readSync` | 파일을 동기적으로 읽습니다 | +| `stat` | 파일의 상태를 읽습니다 | +| `statSync` | 파일의 상태를 동기적으로 읽습니다 | +| `render` | 파일을 생성합니다 | +| `renderSync` | 파일을 동기적으로 생성합니다 | [util.Pattern]: https://github.com/hexojs/hexo-util#patternrule diff --git a/source/ko/api/console.md b/source/ko/api/console.md index d7c08e49bd..644d537b9a 100644 --- a/source/ko/api/console.md +++ b/source/ko/api/console.md @@ -1,21 +1,22 @@ --- title: Console --- + Console은 Hexo와 사용자 간의 교두보 역할을 합니다. 사용 가능한 console 명령어를 등록하고 설명합니다. ## 개요 -``` js -hexo.extend.console.register(name, desc, options, function(args){ +```js +hexo.extend.console.register(name, desc, options, function (args) { // ... }); ``` -인자 | 설명 ---- | --- -`name` | 이름 -`desc` | 설명 -`options`| 옵션 +| 인자 | 설명 | +| --------- | ---- | +| `name` | 이름 | +| `desc` | 설명 | +| `options` | 옵션 | `args` 인자는 사용자가 터미널에 입력한 값을 포함하여 함수 내로 전달됩니다. [Minimist]에 의해 파싱됩니다. @@ -25,8 +26,10 @@ hexo.extend.console.register(name, desc, options, function(args){ Console 명령어의 사용법의 예시입니다: -``` js -{usage: '[layout] <title>'} +```js +{ + usage: "[layout] <title>"; +} // hexo new [layout] <title> ``` @@ -34,12 +37,12 @@ Console 명령어의 사용법의 예시입니다: Console 명령어의 각 인자에 대한 예시입니다: -``` js +```js { arguments: [ - {name: 'layout', desc: 'Post layout'}, - {name: 'title', desc: 'Post title'} - ] + { name: "layout", desc: "Post layout" }, + { name: "title", desc: "Post title" }, + ]; } ``` @@ -47,11 +50,9 @@ Console 명령어의 각 인자에 대한 예시입니다: Console 명령어의 각 옵션에 대한 예시입니다: -``` js +```js { - options: [ - {name: '-r, --replace', desc: 'Replace existing files'} - ] + options: [{ name: "-r, --replace", desc: "Replace existing files" }]; } ``` @@ -61,10 +62,14 @@ Console 명령어에 대한 더 자세한 정보입니다. ## 예시 -``` js -hexo.extend.console.register('config', 'Display configuration', function(args){ - console.log(hexo.config); -}); +```js +hexo.extend.console.register( + "config", + "Display configuration", + function (args) { + console.log(hexo.config); + }, +); ``` [Minimist]: https://github.com/substack/minimist diff --git a/source/ko/api/deployer.md b/source/ko/api/deployer.md index 9dff155173..5322fb3937 100644 --- a/source/ko/api/deployer.md +++ b/source/ko/api/deployer.md @@ -1,12 +1,13 @@ --- title: Deployer --- + Deployer는 복잡한 명령어를 사용하지 않고도 사용자가 사이트를 원격 서버에 빠르게 deploy할 수 있게 도와줍니다. ## 개요 -``` js -hexo.extend.deployer.register(name, function(args){ +```js +hexo.extend.deployer.register(name, function (args) { // ... }); ``` diff --git a/source/ko/api/events.md b/source/ko/api/events.md index 616a15b46d..81de30035d 100644 --- a/source/ko/api/events.md +++ b/source/ko/api/events.md @@ -1,6 +1,7 @@ --- title: Events --- + Hexo는 [EventEmitter]를 상속합니다. `on` 메소드를 사용하여 Hexo가 emit한 이벤트를 listen할 수 있습니다. 그리고 `emit`메소드를 사용하여 이벤트를 emit합니다. 더 자세한 정보는 Node.js API 문서를 참고해 주시기 바랍니다. ### deployBefore @@ -27,16 +28,16 @@ Hexo가 종료되기 전에 emit합니다. 새로운 포스트가 생성된 후에 emit합니다. 이 이벤트는 포스트 데이터를 반환합니다: -``` js -hexo.on('new', function(post){ +```js +hexo.on("new", function (post) { // }); ``` -데이터 | 설명 ---- | --- -`post.path` | 포스트 파일의 전체경로 -`post.content` | 포스트 파일의 컨텐츠 +| 데이터 | 설명 | +| -------------- | ---------------------- | +| `post.path` | 포스트 파일의 전체경로 | +| `post.content` | 포스트 파일의 컨텐츠 | ### processBefore diff --git a/source/ko/api/filter.md b/source/ko/api/filter.md index f5bad3105d..7db4b1e0d5 100644 --- a/source/ko/api/filter.md +++ b/source/ko/api/filter.md @@ -1,11 +1,12 @@ --- title: Filter --- + Filter는 특정한 데이터를 수정할 때 사용합니다. Hexo는 데이터를 filter로 순차적으로 전달하고 filter들은 교대로 데이터를 수정할 수 있습니다. 이 컨셉은 [WordPress](http://codex.wordpress.org/Plugin_API#Filters)에서 차용하였습니다. ## 개요 -``` js +```js hexo.extend.filter.register(type, function() { // User configuration const { config } = this; @@ -22,69 +23,69 @@ hexo.extend.filter.register(type, function() { ## Filter의 실행 -``` js +```js hexo.extend.filter.exec(type, data, options); hexo.extend.filter.execSync(type, data, options); ``` -옵션 | 설명 ---- | --- -`context` | Context -`args` | 인자. 이 값은 배열(array)입니다. +| 옵션 | 설명 | +| --------- | -------------------------------- | +| `context` | Context | +| `args` | 인자. 이 값은 배열(array)입니다. | Filter의 첫 번째 인자는 `data` 입니다. 다음 filter로 전달 된 `data`는 새 값으로 변경되어 반환될 수 있습니다. 아무런 값도 반환되지 않았다면 data의 값이 변경되지 않았다는 의미입니다. Filter의 다른 인자를 지정하기 위해 `args`를 사용할 수도 있습니다. 아래 예시를 봐주세요. -``` js -hexo.extend.filter.register('test', function(data, arg1, arg2){ +```js +hexo.extend.filter.register("test", function (data, arg1, arg2) { // data === 'some data' // arg1 === 'foo' // arg2 === 'bar' - return 'something'; + return "something"; }); -hexo.extend.filter.register('test', function(data, arg1, arg2){ +hexo.extend.filter.register("test", function (data, arg1, arg2) { // data === 'something' }); -hexo.extend.filter.exec('test', 'some data', { - args: ['foo', 'bar'] +hexo.extend.filter.exec("test", "some data", { + args: ["foo", "bar"], }); ``` Filter를 실행하기 위해 아래 메소드들을 사용할 수도 있습니다. -``` js +```js hexo.execFilter(type, data, options); hexo.execFilterSync(type, data, options); ``` ## Filter의 등록 해제 -``` js +```js hexo.extend.filter.unregister(type, filter); ``` **Example** -``` js +```js // Unregister a filter which is registered with named function const filterFn = (data) => { - data = 'something'; + data = "something"; return data; }; -hexo.extend.filter.register('example', filterFn); +hexo.extend.filter.register("example", filterFn); -hexo.extend.filter.unregister('example', filterFn); +hexo.extend.filter.unregister("example", filterFn); ``` -``` js +```js // Unregister a filter which is registered with commonjs module -hexo.extend.filter.register('example', require('path/to/filter')); +hexo.extend.filter.register("example", require("path/to/filter")); -hexo.extend.filter.unregister('example', require('path/to/filter')); +hexo.extend.filter.unregister("example", require("path/to/filter")); ``` ## Filter 목록 @@ -97,8 +98,8 @@ Post가 생성되기 전에 실행됩니다. 실행 단계에 대해 더 알아 아래 예시는 title을 소문자로 변경하는 것을 보여줍니다. -``` js -hexo.extend.filter.register('before_post_render', function(data){ +```js +hexo.extend.filter.register("before_post_render", function (data) { data.title = data.title.toLowerCase(); return data; }); @@ -111,9 +112,12 @@ Executed after a post is rendered. 실행 단계에 대해 더 알아보시길 아래 예시는 `@username`을 Twitter link로 대체하는 것을 보여줍니다. -``` js -hexo.extend.filter.register('after_post_render', function(data){ - data.content = data.content.replace(/@(\d+)/, '<a href="http://twitter.com/$1">#$1</a>'); +```js +hexo.extend.filter.register("after_post_render", function (data) { + data.content = data.content.replace( + /@(\d+)/, + '<a href="http://twitter.com/$1">#$1</a>', + ); return data; }); ``` @@ -122,8 +126,8 @@ hexo.extend.filter.register('after_post_render', function(data){ Hexo가 종료되기 전에 실행됩니다. -- `hexo.exit`가 호출되는 즉시 실행됩니다. -``` js -hexo.extend.filter.register('before_exit', function(){ +```js +hexo.extend.filter.register("before_exit", function () { // ... }); ``` @@ -132,8 +136,8 @@ hexo.extend.filter.register('before_exit', function(){ 생성(generation)이 시작되기 전에 실행됩니다. -``` js -hexo.extend.filter.register('before_generate', function(){ +```js +hexo.extend.filter.register("before_generate", function () { // ... }); ``` @@ -142,8 +146,8 @@ hexo.extend.filter.register('before_generate', function(){ 생성(generation)이 끝난 후에 실행됩니다. -``` js -hexo.extend.filter.register('after_generate', function(){ +```js +hexo.extend.filter.register("after_generate", function () { // ... }); ``` @@ -154,8 +158,8 @@ hexo.extend.filter.register('after_generate', function(){ 아래 예시는 템플릿의 지역 변수에 현재 시간을 추가합니다. -``` js -hexo.extend.filter.register('template_locals', function(locals){ +```js +hexo.extend.filter.register("template_locals", function (locals) { locals.now = Date.now(); return locals; }); @@ -165,8 +169,8 @@ hexo.extend.filter.register('template_locals', function(locals){ Hexo가 초기화 작업이 완료된 후 실행됩니다. -- `hexo.init`이 완료되는 즉시 실행됩니다. -``` js -hexo.extend.filter.register('after_init', function(){ +```js +hexo.extend.filter.register("after_init", function () { // ... }); ``` @@ -175,8 +179,8 @@ hexo.extend.filter.register('after_init', function(){ 새로운 포스트가 생성될 때 포스트의 경로를 결정하기 위해 실행됩니다. -``` js -hexo.extend.filter.register('new_post_path', function(data, replace){ +```js +hexo.extend.filter.register("new_post_path", function (data, replace) { // ... }); ``` @@ -185,8 +189,8 @@ hexo.extend.filter.register('new_post_path', function(data, replace){ Post의 permalink를 결정하기 위해 사용합니다. -``` js -hexo.extend.filter.register('post_permalink', function(data){ +```js +hexo.extend.filter.register("post_permalink", function (data) { // ... }); ``` @@ -201,10 +205,10 @@ hexo.extend.filter.register('post_permalink', function(data){ 아래 예시는 response header에 `X-Powered-By: Hexo`를 추가합니다. -``` js -hexo.extend.filter.register('server_middleware', function(app){ - app.use(function(req, res, next){ - res.setHeader('X-Powered-By', 'Hexo'); +```js +hexo.extend.filter.register("server_middleware", function (app) { + app.use(function (req, res, next) { + res.setHeader("X-Powered-By", "Hexo"); next(); }); }); diff --git a/source/ko/api/generator.md b/source/ko/api/generator.md index 93bd805f90..064c3aabaf 100644 --- a/source/ko/api/generator.md +++ b/source/ko/api/generator.md @@ -1,12 +1,13 @@ --- title: Generator --- + Generator는 처리된 파일들을 기준으로 경로(route)를 생성합니다. ## 개요 -``` js -hexo.extend.generator.register(name, function(locals){ +```js +hexo.extend.generator.register(name, function (locals) { // ... }); ``` @@ -15,27 +16,27 @@ hexo.extend.generator.register(name, function(locals){ ## 경로(route) 업데이트 -``` js -hexo.extend.generator.register('test', function(locals){ +```js +hexo.extend.generator.register("test", function (locals) { // Object return { - path: 'foo', - data: 'foo' + path: "foo", + data: "foo", }; // Array return [ - {path: 'foo', data: 'foo'}, - {path: 'bar', data: 'bar'} + { path: "foo", data: "foo" }, + { path: "bar", data: "bar" }, ]; }); ``` -속성 | 설명 ---- | --- -`path` | 접두사 `/`를 포함하지 않는 경로. -`data` | 데이터 -`layout` | 레이아웃. 렌더링할 레이아웃을 지정합니다. 이 값은 string 또는 array입니다. 이 값이 무시된다면 `data`의 직접적인 경로가 반환됩니다. +| 속성 | 설명 | +| -------- | ---------------------------------------------------------------------------------------------------------------------------------- | +| `path` | 접두사 `/`를 포함하지 않는 경로. | +| `data` | 데이터 | +| `layout` | 레이아웃. 렌더링할 레이아웃을 지정합니다. 이 값은 string 또는 array입니다. 이 값이 무시된다면 `data`의 직접적인 경로가 반환됩니다. | 소스 파일들이 업데이트 되면, Hexo는 모든 generator들을 실행하고 경로(route)를 재구성합니다. **제발 라우터에 직접 접근하지 마시고 데이터를 리턴하세요.** @@ -47,13 +48,13 @@ Archive page를 `archives/index.html`에 생성합니다. 우리는 모든 포 다음, 테마 템플릿 렌더링을 위한 `layout` 속성을 설정합니다. 아래 예시에서 두 개의 레이아웃 설정을 확인할 수 있습니다. 만약 `archive` 레이아웃이 존재하지 않는다면 `index` 레이아웃이 사용될 것입니다. -``` js -hexo.extend.generator.register('archive', function(locals){ +```js +hexo.extend.generator.register("archive", function (locals) { return { - path: 'archives/index.html', + path: "archives/index.html", data: locals.posts, - layout: ['archive', 'index'] - } + layout: ["archive", "index"], + }; }); ``` @@ -61,14 +62,14 @@ hexo.extend.generator.register('archive', function(locals){ Hexo 공식 툴인 [hexo-pagination]을 사용하여 간편하게 pagination을 구현할 수 있습니다. -``` js -var pagination = require('hexo-pagination'); +```js +var pagination = require("hexo-pagination"); -hexo.extend.generator.register('archive', function(locals){ - return pagination('archives/index.html', locals.posts, { +hexo.extend.generator.register("archive", function (locals) { + return pagination("archives/index.html", locals.posts, { perPage: 10, - layout: ['archive', 'index'], - data: {} + layout: ["archive", "index"], + data: {}, }); }); ``` @@ -77,13 +78,13 @@ hexo.extend.generator.register('archive', function(locals){ `locals.posts`에 포함된 모든 포스트들을 순회하고 각각의 포스트에 대한 경로(route)를 생성합니다. -``` js -hexo.extend.generator.register('post', function(locals){ - return locals.posts.map(function(post){ +```js +hexo.extend.generator.register("post", function (locals) { + return locals.posts.map(function (post) { return { path: post.path, data: post, - layout: 'post' + layout: "post", }; }); }); @@ -93,15 +94,15 @@ hexo.extend.generator.register('post', function(locals){ 이 시점에 우리는 명시적인 데이터를 반환하지 않고 필요한 경우에만 경로(route)는 `fs.ReadStream`를 생성하기 위해 함수에 `data`를 설정합니다. -``` js -var fs = require('hexo-fs'); +```js +var fs = require("hexo-fs"); -hexo.extend.generator.register('asset', function(locals){ +hexo.extend.generator.register("asset", function (locals) { return { - path: 'file.txt', - data: function(){ - return fs.createReadStream('path/to/file.txt') - } + path: "file.txt", + data: function () { + return fs.createReadStream("path/to/file.txt"); + }, }; }); ``` diff --git a/source/ko/api/helper.md b/source/ko/api/helper.md index 4457fb8525..5acd6bbf27 100644 --- a/source/ko/api/helper.md +++ b/source/ko/api/helper.md @@ -1,25 +1,26 @@ --- title: Helper --- + Helper는 템플릿에 쉽고 빠르게 정보(snippet)을 추가할 수 있게 도와줍니다. 우리는 당신이 복잡한 코드를 다룰 때 템플릿 대신 helper를 사용하는 것을 추천합니다. ## 개요 -``` js -hexo.extend.helper.register(name, function(){ +```js +hexo.extend.helper.register(name, function () { // ... }); ``` ## 예시 -``` js -hexo.extend.helper.register('js', function(path){ +```js +hexo.extend.helper.register("js", function (path) { return '<script src="' + path + '"></script>'; }); ``` -``` js +```js <%- js('script.js') %> // <script src="script.js"></script> ``` @@ -34,8 +35,8 @@ Place it under `scripts/` or `themes/<yourtheme>/scripts/` folder. All helpers are executed in the same context. For example, to use [`url_for()`](/docs/helpers#url-for) inside a custom helper: -``` js -hexo.extend.helper.register('lorem', function(path) { +```js +hexo.extend.helper.register("lorem", function (path) { return '<script src="' + this.url_for(path) + '"></script>'; }); ``` @@ -44,6 +45,6 @@ hexo.extend.helper.register('lorem', function(path) { `hexo.extend.helper.get` will return the helper function, but it needs to have hexo as its context, so: -``` js -const url_for = hexo.extend.helper.get('url_for').bind(hexo); +```js +const url_for = hexo.extend.helper.get("url_for").bind(hexo); ``` diff --git a/source/ko/api/index.md b/source/ko/api/index.md index e86cdee681..442c18e4e4 100644 --- a/source/ko/api/index.md +++ b/source/ko/api/index.md @@ -1,6 +1,7 @@ --- title: API --- + 이 문서는 API에 대해 더 자세한 정보를 담고 있습니다. Hexo 소스 코드를 수정하길 원하는 사용자나 새로운 플러그인을 작성하고자 하는 사용자에게 많은 도움이 될 것입니다. 당신이 Hexo의 기본 사용법에 대해 흥미가 있다면 [docs](../docs)를 확인해보세요. 이 문서는 Hexo 3 이상의 버전에 맞추어 작성되었습니다. @@ -9,21 +10,21 @@ title: API 우선, 우리는 Hexo 인스턴스를 생성할 필요가 있습니다. 새로운 인스턴스는 두 개의 인자를 갖게 됩니다. 웹 사이트의 루트 디렉토리를 의미하는 `base_dir`와 초기화 옵션을 가지고 있는 객체입니다. 다음으로, `init` 메소드를 호출함으로써 이 인스턴스를 초기화 합니다. 초기화 시 Hexo는 설정값과 플러그인을 불러옵니다. -``` js -var Hexo = require('hexo'); +```js +var Hexo = require("hexo"); var hexo = new Hexo(process.cwd(), {}); -hexo.init().then(function(){ +hexo.init().then(function () { // ... }); ``` -옵션 | 설명 | 기본값 ---- | --- | --- -`debug` | 디버그 모드를 활성화 합니다. 디버그 메시지는 터미널에 출력되고 루트 디렉토리의 `debug.log`파일에 저장됩니다. | `false` -`safe` | 보호 모드를 활성화 합니다. 플러그인을 불러오지 않습니다. | `false` -`silent` | 조용한 모드를 활성화 합니다. 어떠한 메시지도 터미널에 표시하지 않습니다. | `false` -`config` | 환경 설정 파일의 경로를 지정합니다. | `_config.yml` +| 옵션 | 설명 | 기본값 | +| -------- | ------------------------------------------------------------------------------------------------------------ | ------------- | +| `debug` | 디버그 모드를 활성화 합니다. 디버그 메시지는 터미널에 출력되고 루트 디렉토리의 `debug.log`파일에 저장됩니다. | `false` | +| `safe` | 보호 모드를 활성화 합니다. 플러그인을 불러오지 않습니다. | `false` | +| `silent` | 조용한 모드를 활성화 합니다. 어떠한 메시지도 터미널에 표시하지 않습니다. | `false` | +| `config` | 환경 설정 파일의 경로를 지정합니다. | `_config.yml` | ## 파일 불러오기 @@ -31,12 +32,12 @@ Hexo는 파일을 불러오기 위해 두 가지의 메소드를 지원합니다 두 메소드 모드 파일의 목록을 불러와서 적절한 프로세서로 전달합니다. 모든 파일들이 처리된 후, 경로(route)를 생성하기 위해 generator들을 호출합니다. -``` js -hexo.load().then(function(){ +```js +hexo.load().then(function () { // ... }); -hexo.watch().then(function(){ +hexo.watch().then(function () { // You can call hexo.unwatch() later to stop watching. }); ``` @@ -45,8 +46,8 @@ hexo.watch().then(function(){ Hexo 인스턴스의 `call` 메소드를 통해 모든 콘솔 명령어를 호출할 수 있습니다. 호출할 때는 콘솔 명령어와 옵션 두 개의 인자를 포함합니다. 각각의 콘솔 명령어마다 서로 다른 옵션을 가지고 있습니다. -``` js -hexo.call('generate', {}).then(function(){ +```js +hexo.call("generate", {}).then(function () { // ... }); ``` @@ -55,10 +56,13 @@ hexo.call('generate', {}).then(function(){ `exit`를 호출하여 콘솔 명령어의 성공적/비성공적 종료를 할 수 있습니다. 이 명령어를 통해 Hexo를 정상적으로 종료하고 데이터베이스를 저장한다거나 하는 중요한 동작들을 마무리할 수 있습니다. -``` js -hexo.call('generate').then(function(){ - return hexo.exit(); -}).catch(function(err){ - return hexo.exit(err); -}); +```js +hexo + .call("generate") + .then(function () { + return hexo.exit(); + }) + .catch(function (err) { + return hexo.exit(err); + }); ``` diff --git a/source/ko/api/injector.md b/source/ko/api/injector.md index 04f45be3ce..c44a869b40 100644 --- a/source/ko/api/injector.md +++ b/source/ko/api/injector.md @@ -7,7 +7,7 @@ An injector is used to add static code snippet to the `<head>` or/and `<body>` o ## Synopsis ```js -hexo.extend.injector.register(entry, value, to) +hexo.extend.injector.register(entry, value, to); ``` ### entry `<string>` @@ -40,24 +40,34 @@ Which page will code snippets being injected. - `tag`: Only inject to tag pages (which has `is_tag()` helper being `true`) - Custom layout name could be used as well, see [Writing - Layout](writing#Layout). ----- +--- There are other internal functions, see [hexojs/hexo#4049](https://github.com/hexojs/hexo/pull/4049) for more details. ## Example ```js -const css = hexo.extend.helper.get('css').bind(hexo); -const js = hexo.extend.helper.get('js').bind(hexo); - -hexo.extend.injector.register('head_end', () => { - return css('https://cdn.jsdelivr.net/npm/aplayer@1.10.1/dist/APlayer.min.css'); -}, 'music'); - -hexo.extend.injector.register('body_end', '<script src="https://cdn.jsdelivr.net/npm/aplayer@1.10.1/dist/APlayer.min.js">', 'music'); - -hexo.extend.injector.register('body_end', () => { - return js('/js/jquery.js'); +const css = hexo.extend.helper.get("css").bind(hexo); +const js = hexo.extend.helper.get("js").bind(hexo); + +hexo.extend.injector.register( + "head_end", + () => { + return css( + "https://cdn.jsdelivr.net/npm/aplayer@1.10.1/dist/APlayer.min.css", + ); + }, + "music", +); + +hexo.extend.injector.register( + "body_end", + '<script src="https://cdn.jsdelivr.net/npm/aplayer@1.10.1/dist/APlayer.min.js">', + "music", +); + +hexo.extend.injector.register("body_end", () => { + return js("/js/jquery.js"); }); ``` @@ -69,10 +79,10 @@ Use any of the following options: 1. -``` js -const css = hexo.extend.helper.get('css').bind(hexo); +```js +const css = hexo.extend.helper.get("css").bind(hexo); -hexo.extend.injector.register('head_end', () => { +hexo.extend.injector.register("head_end", () => { const { cssPath } = hexo.config.fooPlugin; return css(cssPath); }); @@ -80,23 +90,23 @@ hexo.extend.injector.register('head_end', () => { 2. -``` js index.js +```js index.js /* global hexo */ -hexo.extend.injector.register('head_end', require('./lib/inject').bind(hexo)) +hexo.extend.injector.register("head_end", require("./lib/inject").bind(hexo)); ``` -``` js lib/inject.js +```js lib/inject.js module.exports = function () { - const css = this.extend.helper.get('css'); + const css = this.extend.helper.get("css"); const { cssPath } = this.config.fooPlugin; return css(cssPath); -} +}; ``` -``` js lib/inject.js +```js lib/inject.js function injectFn() { - const css = this.extend.helper.get('css'); + const css = this.extend.helper.get("css"); const { cssPath } = this.config.fooPlugin; return css(cssPath); } @@ -106,23 +116,23 @@ module.exports = injectFn; 3. -``` js index.js +```js index.js /* global hexo */ -hexo.extend.injector.register('head_end', require('./lib/inject')(hexo)) +hexo.extend.injector.register("head_end", require("./lib/inject")(hexo)); ``` -``` js lib/inject.js +```js lib/inject.js module.exports = (hexo) => () => { - const css = hexo.extend.helper.get('css').bind(hexo); + const css = hexo.extend.helper.get("css").bind(hexo); const { cssPath } = hexo.config.fooPlugin; return css(cssPath); }; ``` -``` js lib/inject.js +```js lib/inject.js const injectFn = (hexo) => { - const css = hexo.extend.helper.get('css').bind(hexo); + const css = hexo.extend.helper.get("css").bind(hexo); const { cssPath } = hexo.config.fooPlugin; return css(cssPath); }; diff --git a/source/ko/api/locals.md b/source/ko/api/locals.md index 8b756c37b5..07bbb1adb9 100644 --- a/source/ko/api/locals.md +++ b/source/ko/api/locals.md @@ -1,26 +1,27 @@ --- title: Local Variables --- + 지역 변수는 템플릿의 `site` 변수처럼 템플릿 렌더링을 위해 사용됩니다. ## 기본적인 변수 -변수 | 설명 ---- | --- -`posts` | 모든 포스트 -`pages` | 모든 페이지 -`categories` | 모든 카테고리 -`tags` | 모든 태그 +| 변수 | 설명 | +| ------------ | ------------- | +| `posts` | 모든 포스트 | +| `pages` | 모든 페이지 | +| `categories` | 모든 카테고리 | +| `tags` | 모든 태그 | ## 변수 얻어오기 -``` js -hexo.locals.get('posts') +```js +hexo.locals.get("posts"); ``` ## 변수 설정 -``` js +```js hexo.locals.set('posts', function(){ return ... }); @@ -28,18 +29,18 @@ hexo.locals.set('posts', function(){ ## 변수 제거 -``` js -hexo.locals.remove('posts'); +```js +hexo.locals.remove("posts"); ``` ## 모든 변수 얻어오기 -``` js +```js hexo.locals.toObject(); ``` ## 캐시 무효화 -``` js +```js hexo.locals.invalidate(); ``` diff --git a/source/ko/api/migrator.md b/source/ko/api/migrator.md index 1a6fdfeef9..b9224ec79f 100644 --- a/source/ko/api/migrator.md +++ b/source/ko/api/migrator.md @@ -1,12 +1,13 @@ --- title: Migrator --- + Migrator는 다른 시스템을 사용하던 사용자가 Hexo로의 마이그레이션을 할 수 있게 도와줍니다. ## 개요 -``` js -hexo.extend.migrator.register(name, function(args){ +```js +hexo.extend.migrator.register(name, function (args) { // ... }); ``` diff --git a/source/ko/api/posts.md b/source/ko/api/posts.md index b48e04c8e0..57fab5b771 100644 --- a/source/ko/api/posts.md +++ b/source/ko/api/posts.md @@ -1,55 +1,56 @@ --- title: Posts --- + ## 포스트 생성 -``` js +```js hexo.post.create(data, replace); ``` -인자 | 설명 ---- | --- -`data` | 데이터 -`replace` | 존재하는 파일을 대체함 +| 인자 | 설명 | +| --------- | ---------------------- | +| `data` | 데이터 | +| `replace` | 존재하는 파일을 대체함 | 포스트의 속성은 `data`에 정의할 수 있습니다. 아래의 표는 완벽하진 않습니다. 추가 속성은 앞의 내용(front-matter)에 추가할 수 있습니다. -데이터 | 설명 ---- | --- -`title` | 타이틀 -`slug` | URL -`layout` | 레이아웃. 기본 값은 `default_layout` 설정을 따릅니다. -`path` | 경로. Hexo는 기본적으로 `new_post_path`를 기반으로 경로를 설정합니다. -`date` | 날짜. 기본 값은 현재 시간입니다. +| 데이터 | 설명 | +| -------- | --------------------------------------------------------------------- | +| `title` | 타이틀 | +| `slug` | URL | +| `layout` | 레이아웃. 기본 값은 `default_layout` 설정을 따릅니다. | +| `path` | 경로. Hexo는 기본적으로 `new_post_path`를 기반으로 경로를 설정합니다. | +| `date` | 날짜. 기본 값은 현재 시간입니다. | ## Draft 배포 -``` js +```js hexo.post.publish(data, replace); ``` -인자 | 설명 ---- | --- -`data` | 데이터 -`replace` | 존재하는 파일을 대체함 +| 인자 | 설명 | +| --------- | ---------------------- | +| `data` | 데이터 | +| `replace` | 존재하는 파일을 대체함 | 포스트의 속성은 `data`에 정의할 수 있습니다. 아래의 표는 완벽하진 않습니다. 추가 속성은 앞의 내용(front-matter)에 추가할 수 있습니다. -데이터 | 설명 ---- | --- -`slug` | 파일명 (Required) -`layout` | 레이아웃. 기본 값은 `default_layout` 설정을 따릅니다. +| 데이터 | 설명 | +| -------- | ----------------------------------------------------- | +| `slug` | 파일명 (Required) | +| `layout` | 레이아웃. 기본 값은 `default_layout` 설정을 따릅니다. | ## 그리기 (Render) -``` js +```js hexo.post.render(source, data); ``` -인자 | 설명 ---- | --- -`source` | 파일의 전체 경로 (Optional) -`data` | 데이터 +| 인자 | 설명 | +| -------- | --------------------------- | +| `source` | 파일의 전체 경로 (Optional) | +| `data` | 데이터 | 데이터는 반드시 `content` 속성 내에 포함되어야 합니다. 그렇지 않을 경우, Hexo는 원본 파일을 읽으려고 시도할 것입니다. 이 함수의 실행 단계는 아래와 같습니다. diff --git a/source/ko/api/processor.md b/source/ko/api/processor.md index 0edf4b29bd..4a19258690 100644 --- a/source/ko/api/processor.md +++ b/source/ko/api/processor.md @@ -1,13 +1,14 @@ --- title: Processor --- + `source` 폴더 내의 소스 파일들을 처리할 때 프로세서를 사용합니다. ## 개요 -``` js -hexo.extend.processor.register(rule, function(file){ - // ... +```js +hexo.extend.processor.register(rule, function (file) { + // ... }); ``` diff --git a/source/ko/api/renderer.md b/source/ko/api/renderer.md index 6e00871f79..0b759708c3 100644 --- a/source/ko/api/renderer.md +++ b/source/ko/api/renderer.md @@ -1,70 +1,85 @@ --- title: Renderer --- + Renderer는 내용들을 그릴(render) 때 사용합니다. ## 개요 -``` js -hexo.extend.renderer.register(name, output, function(data, options){ - // ... -}, sync); +```js +hexo.extend.renderer.register( + name, + output, + function (data, options) { + // ... + }, + sync, +); ``` -인자 | 설명 ---- | --- -`name` | 입력 파일의 확장자 (소문자, '.' 사용 불가) -`output` | 출력 파일의 확장자 (소문자, '.' 사용 불가) -`sync` | 동기(Sync) 모드 +| 인자 | 설명 | +| -------- | ------------------------------------------ | +| `name` | 입력 파일의 확장자 (소문자, '.' 사용 불가) | +| `output` | 출력 파일의 확장자 (소문자, '.' 사용 불가) | +| `sync` | 동기(Sync) 모드 | 두 개의 인자가 render 함수로 전달됩니다: -인자 | 설명 ---- | --- -`data` |두 개의 속성을 포함합니다: 파일 경로인 `path`와 파일 컨텐츠인 `text`. `path`는 없어도 됩니다. -`option` | 옵션 +| 인자 | 설명 | +| -------- | --------------------------------------------------------------------------------------------- | +| `data` | 두 개의 속성을 포함합니다: 파일 경로인 `path`와 파일 컨텐츠인 `text`. `path`는 없어도 됩니다. | +| `option` | 옵션 | ## 예시 ### 비동기(Async) 모드 -``` js -var stylus = require('stylus'); +```js +var stylus = require("stylus"); // Callback -hexo.extend.renderer.register('styl', 'css', function(data, options, callback){ - stylus(data.text).set('filename', data.path).render(callback); -}); +hexo.extend.renderer.register( + "styl", + "css", + function (data, options, callback) { + stylus(data.text).set("filename", data.path).render(callback); + }, +); // Promise -hexo.extend.renderer.register('styl', 'css', function(data, options){ - return new Promise(function(resolve, reject){ - resolve('test'); +hexo.extend.renderer.register("styl", "css", function (data, options) { + return new Promise(function (resolve, reject) { + resolve("test"); }); }); ``` ### 동기(Sync) Mode -``` js -var ejs = require('ejs'); - -hexo.extend.renderer.register('ejs', 'html', function(data, options){ - options.filename = data.path; - return ejs.render(data.text, options); -}, true); +```js +var ejs = require("ejs"); + +hexo.extend.renderer.register( + "ejs", + "html", + function (data, options) { + options.filename = data.path; + return ejs.render(data.text, options); + }, + true, +); ``` ### Disable Nunjucks tags Nunjucks tags `{{ }}` or `{% %}` (utilized by [tag plugin](/docs/tag-plugins)) are processed by default, to disable: -``` js +```js function lessFn(data, options) { // do something } -lessFn.disableNunjucks = true +lessFn.disableNunjucks = true; -hexo.extend.renderer.register('less', 'css', lessFn); +hexo.extend.renderer.register("less", "css", lessFn); ``` diff --git a/source/ko/api/rendering.md b/source/ko/api/rendering.md index a38a0354b6..9452ad5ff7 100644 --- a/source/ko/api/rendering.md +++ b/source/ko/api/rendering.md @@ -1,14 +1,15 @@ --- title: Rendering --- + Hexo에서 파일 또는 문자열을 렌더링 하기위해 두 가지의 메소드를 사용할 수 있습니다. 비동기 메소드인 `hexo.render.render`와 동기 메소드인 `hexo.render.renderSync`입니다. 두 가지의 메소드는 매우 유사하기 때문에 이 문서에서는 비동기 메소드인 `hexo.render.render` 에 대해 알아보겠습니다. ## 문자열의 렌더링 문자열을 렌더링하기 위해 Hexo가 어떤 엔진을 사용하여 렌더링하면 되는지 `engine` 을 통해 알려줘야 합니다. -``` js -hexo.render.render({text: 'example', engine: 'swig'}).then(function(result){ +```js +hexo.render.render({ text: "example", engine: "swig" }).then(function (result) { // ... }); ``` @@ -17,8 +18,8 @@ hexo.render.render({text: 'example', engine: 'swig'}).then(function(result){ 파일을 렌더링할 때에는 `engine`을 반드시 지정할 필요는 없습니다. 왜냐하면 Hexo는 파일 확장자를 보고 자동으로 연관된 렌더링 엔진을 찾기 때문입니다. 물론, 명시적으로 `engine`을 지정해도 상관 없습니다. -``` js -hexo.render.render({path: 'path/to/file.swig'}).then(function(result){ +```js +hexo.render.render({ path: "path/to/file.swig" }).then(function (result) { // ... }); ``` @@ -27,8 +28,8 @@ hexo.render.render({path: 'path/to/file.swig'}).then(function(result){ 두 번째 인자인 옵션은 꼭 넣지 않아도 됩니다. -``` js -hexo.render.render({text: ''}, {foo: 'foo'}).then(function(result){ +```js +hexo.render.render({ text: "" }, { foo: "foo" }).then(function (result) { // ... }); ``` @@ -37,10 +38,10 @@ hexo.render.render({text: ''}, {foo: 'foo'}).then(function(result){ 렌더링이 완료되면 Hexo는 적절한 `after_render` filter를 실행합니다. 예를 들어, 우리는 이 기능을 JavaScript minifier를 구현하는데 사용할 수 있습니다. -``` js -var UglifyJS = require('uglify-js'); +```js +var UglifyJS = require("uglify-js"); -hexo.extend.filter.register('after_render:js', function(str, data){ +hexo.extend.filter.register("after_render:js", function (str, data) { var result = UglifyJS.minify(str); return result.code; }); @@ -50,30 +51,30 @@ hexo.extend.filter.register('after_render:js', function(str, data){ 파일의 경로가 렌더링 가능한지 확인하기 위해 `isRenderable` 또는 `isRenderableSync` 메소드를 사용할 수 있습니다. 이 메소드는 적절한 렌더러가 등록되어 있을 때에만 true를 반환합니다. -``` js -hexo.render.isRenderable('layout.swig') // true -hexo.render.isRenderable('image.png') // false +```js +hexo.render.isRenderable("layout.swig"); // true +hexo.render.isRenderable("image.png"); // false ``` ## 출력 확장자 가져오기 `getOutput`메소드를 사용하면 렌더링된 출력의 확장자를 불러올 수 있습니다. 파일이 렌더링 불가능하다면, 이 메소드는 빈 문자열을 반환할 것입니다. -``` js -hexo.render.getOutput('layout.swig') // html -hexo.render.getOutput('image.png') // ''' +```js +hexo.render.getOutput("layout.swig"); // html +hexo.render.getOutput("image.png"); // ''' ``` ## Disable Nunjucks tags If you are not using a [tag plugin](/docs/tag-plugins) and want to use `{{ }}` or `{% %}` in your post without using content [escaping](/docs/troubleshooting#Escape-Contents), you can disable processing of Nunjucks tag in existing renderer by: -``` js +```js // following example only applies to '.md' file extension // you may need to cover other extensions, e.g. '.markdown', '.mkd', etc -const renderer = hexo.render.renderer.get('md') +const renderer = hexo.render.renderer.get("md"); if (renderer) { - renderer.disableNunjucks = true - hexo.extend.renderer.register('md', 'html', renderer) + renderer.disableNunjucks = true; + hexo.extend.renderer.register("md", "html", renderer); } ``` diff --git a/source/ko/api/router.md b/source/ko/api/router.md index 552c8167a8..c7071c7e7d 100644 --- a/source/ko/api/router.md +++ b/source/ko/api/router.md @@ -1,15 +1,16 @@ --- title: Router --- + Router는 사이트의 모든 경로를 저장합니다. ## 경로 가져오기 `get` 메소드는 [Stream]을 반환합니다. 아래는 특정한 목적지로 가기 위한 경로 데이터를 저장하는 동작 예시입니다. -``` js -var data = hexo.route.get('index.html'); -var dest = fs.createWriteStream('somewhere'); +```js +var data = hexo.route.get("index.html"); +var dest = fs.createWriteStream("somewhere"); data.pipe(dest); ``` @@ -18,32 +19,32 @@ data.pipe(dest); `set` 메소드는 문자열과 [Buffer] 또는 함수를 통해 얻어옵니다. -``` js +```js // String -hexo.route.set('index.html', 'index') +hexo.route.set("index.html", "index"); // Buffer -hexo.route.set('index.html', new Buffer('index')); +hexo.route.set("index.html", new Buffer("index")); // Function (Promise) -hexo.route.set('index.html', function(){ - return new Promise(function(resolve, reject){ - resolve('index'); +hexo.route.set("index.html", function () { + return new Promise(function (resolve, reject) { + resolve("index"); }); }); // Function (Callback) -hexo.route.set('index.html', function(callback){ - callback(null, 'index'); +hexo.route.set("index.html", function (callback) { + callback(null, "index"); }); ``` 경로가 수정되었는지 아닌지에 대해 boolean값을 통해 확인할 수 있습니다. 이는 수정되지 않은 파일을 무시하여 파일의 빠른 생성을 도와줍니다. -``` js -hexo.route.set('index.html', { - data: 'index', - modified: false +```js +hexo.route.set("index.html", { + data: "index", + modified: false, }); // hexo.route.isModified('index.html') => false @@ -51,13 +52,13 @@ hexo.route.set('index.html', { ## 경로 제거하기 -``` js -hexo.route.remove('index.html'); +```js +hexo.route.remove("index.html"); ``` ## 경로(route) 목록 가져오기 -``` js +```js hexo.route.list(); ``` @@ -65,8 +66,8 @@ hexo.route.list(); `format` 메소드는 문자열을 사용 가능한 경로로 변환해줍니다. -``` js -hexo.route.format('archives/'); +```js +hexo.route.format("archives/"); // archives/index.html ``` diff --git a/source/ko/api/scaffolds.md b/source/ko/api/scaffolds.md index 47d1c31d95..4a830aff28 100644 --- a/source/ko/api/scaffolds.md +++ b/source/ko/api/scaffolds.md @@ -1,20 +1,21 @@ --- title: Scaffolds --- + ## Scaffold 얻어오기 -``` js +```js hexo.scaffold.get(name); ``` ## Scaffold 설정하기 -``` js +```js hexo.scaffold.set(name, content); ``` ## Scaffold의 제거 -``` js +```js hexo.scaffold.remove(name); ``` diff --git a/source/ko/api/tag.md b/source/ko/api/tag.md index 50b65041fc..d67fee0816 100644 --- a/source/ko/api/tag.md +++ b/source/ko/api/tag.md @@ -1,14 +1,19 @@ --- title: Tag --- + 태그는 사용자가 포스트 내부에 정보(snippet)을 쉽고 빠르게 삽입할 수 있게 도와줍니다. ## 개요 -``` js -hexo.extend.tag.register(name, function(args, content){ - // ... -}, options); +```js +hexo.extend.tag.register( + name, + function (args, content) { + // ... + }, + options, +); ``` `args`, `content` 두 개의 인자가 함수를 통해 전달됩니다. `args`는 태그 플러그인으로 전달되는 인자들을 포함하고 `content`는 태그 플러그인에서 사용할 포장된 내용(wrapped content)을 나타냅니다. @@ -19,22 +24,22 @@ Hexo 3에서 비동기 렌더링을 도입한 이후, 우리는 렌더링을 위 Use `unregister()` to replace existing [tag plugins](/docs/tag-plugins) with custom functions. -``` js +```js hexo.extend.tag.unregister(name); ``` **Example** -``` js +```js const tagFn = (args, content) => { - content = 'something'; + content = "something"; return content; }; // https://hexo.io/docs/tag-plugins#YouTube -hexo.extend.tag.unregister('youtube'); +hexo.extend.tag.unregister("youtube"); -hexo.extend.tag.register('youtube', tagFn); +hexo.extend.tag.register("youtube", tagFn); ``` ## 옵션 @@ -53,10 +58,14 @@ end 태그를 사용합니다. 기본값은 `false`입니다. Youtube video를 삽입하는 예시입니다. -``` js -hexo.extend.tag.register('youtube', function(args){ +```js +hexo.extend.tag.register("youtube", function (args) { var id = args[0]; - return '<div class="video-container"><iframe width="560" height="315" src="http://www.youtube.com/embed/' + id + '" frameborder="0" allowfullscreen></iframe></div>'; + return ( + '<div class="video-container"><iframe width="560" height="315" src="http://www.youtube.com/embed/' + + id + + '" frameborder="0" allowfullscreen></iframe></div>' + ); }); ``` @@ -64,29 +73,43 @@ hexo.extend.tag.register('youtube', function(args){ Pull quote를 삽입하는 예시입니다. -``` js -hexo.extend.tag.register('pullquote', function(args, content){ - var className = args.join(' '); - return '<blockquote class="pullquote' + className + '">' + content + '</blockquote>'; -}, {ends: true}); +```js +hexo.extend.tag.register( + "pullquote", + function (args, content) { + var className = args.join(" "); + return ( + '<blockquote class="pullquote' + + className + + '">' + + content + + "</blockquote>" + ); + }, + { ends: true }, +); ``` ### 비동기 렌더링 파일을 삽입하는 예시입니다. -``` js -var fs = require('hexo-fs'); -var pathFn = require('path'); - -hexo.extend.tag.register('include_code', function(args){ - var filename = args[0]; - var path = pathFn.join(hexo.source_dir, filename); - - return fs.readFile(path).then(function(content){ - return '<pre><code>' + content + '</code></pre>'; - }); -}, {async: true}); +```js +var fs = require("hexo-fs"); +var pathFn = require("path"); + +hexo.extend.tag.register( + "include_code", + function (args) { + var filename = args[0]; + var path = pathFn.join(hexo.source_dir, filename); + + return fs.readFile(path).then(function (content) { + return "<pre><code>" + content + "</code></pre>"; + }); + }, + { async: true }, +); ``` ## Front-matter and user configuration @@ -95,7 +118,7 @@ Any of the following options is valid: 1. -``` js +```js hexo.extend.tag.register('foo', function (args) { const [firstArg] = args; @@ -120,11 +143,11 @@ hexo.extend.tag.register('foo', function (args) { 2. -``` js index.js -hexo.extend.tag.register('foo', require('./lib/foo')(hexo)); +```js index.js +hexo.extend.tag.register("foo", require("./lib/foo")(hexo)); ``` -``` js lib/foo.js +```js lib/foo.js module.exports = hexo => { return function fooFn(args) { const [firstArg] = args; diff --git a/source/ko/api/themes.md b/source/ko/api/themes.md index 6644240082..588567f8df 100644 --- a/source/ko/api/themes.md +++ b/source/ko/api/themes.md @@ -1,23 +1,24 @@ --- title: Themes --- + `hexo.theme`는 [Box](box.html)를 상속하며, 템플릿을 저장합니다. ## View 얻어오기 -``` js +```js hexo.theme.getView(path); ``` ## View 설정하기 -``` js +```js hexo.theme.setView(path, data); ``` ## View 제거하기 -``` js +```js hexo.theme.removeView(path); ``` @@ -25,10 +26,10 @@ hexo.theme.removeView(path); View는 `render`와 `renderSync` 두 개의 메소드를 가지고 있습니다. 이 두 메소드들은 같은 동작을 수행하지만 `render`는 비동기적으로 동작하고 `renderSync`는 동기적으로 동작합니다. 단순한 설명을 위해, 여기에서는 `render`에 대해서만 다루겠습니다. -``` js -var view = hexo.theme.getView('layout.swig'); +```js +var view = hexo.theme.getView("layout.swig"); -view.render({foo: 1, bar: 2}).then(function(result){ +view.render({ foo: 1, bar: 2 }).then(function (result) { // ... }); ``` diff --git a/source/ko/docs/asset-folders.md b/source/ko/docs/asset-folders.md index 7a7e83f4b2..c63a0f6613 100644 --- a/source/ko/docs/asset-folders.md +++ b/source/ko/docs/asset-folders.md @@ -1,6 +1,7 @@ --- title: Asset Folders --- + ## 전역 Asset 폴더 Asset은 포스트 파일이 아니며 `source` 폴더에 위치합니다. 이미지, CSS, JavaScript 파일이 이에 해당합니다. 예를 들어, Hexo에서 이미지 파일을 사용하고 싶을 때 간단하게 `source/images` 디렉토리에 넣어두면 됩니다. 포스트 내에서 사용하고 싶을 때는 그냥 이렇게 부르면 됩니다. `![](/images/image.jpg)` @@ -9,7 +10,7 @@ Asset은 포스트 파일이 아니며 `source` 폴더에 위치합니다. 이 꾸준히 이미지 또는 다른 asset들을 제공해야 하고 포스트 단위로 asset을 관리하고 싶어하는 사용자들을 위해 Hexo는 asset을 관리할 수 있는 방법을 제공합니다. `_config.yml` 파일의 `post_asset_folder`을 true로 설정하면 됩니다. -``` yaml _config.yml +```yaml _config.yml post_asset_folder: true ``` @@ -42,7 +43,7 @@ Asset 폴더 관리 기능을 활성화 시켰다면, Hexo는 당신이 `hexo ne To enable: -``` yml _config.yml +```yml _config.yml post_asset_folder: true marked: prependRoot: true diff --git a/source/ko/docs/commands.md b/source/ko/docs/commands.md index 3bed62adc6..5609548e5e 100644 --- a/source/ko/docs/commands.md +++ b/source/ko/docs/commands.md @@ -4,7 +4,7 @@ title: Commands ## init -``` bash +```bash $ hexo init [folder] ``` @@ -17,28 +17,28 @@ This command is a shortcut that runs the following steps: ## new -``` bash +```bash $ hexo new [layout] <title> ``` -새 글(article)을 생성합니다. `layout`이 준비되어 있지 않다면, Hexo는 [_config.yml](configuration.html)에 정의된 `default_layout`을 사용합니다. 만약 `title`에 공백이 포함된다면 따옴표로 감싸주세요. +새 글(article)을 생성합니다. `layout`이 준비되어 있지 않다면, Hexo는 [\_config.yml](configuration.html)에 정의된 `default_layout`을 사용합니다. 만약 `title`에 공백이 포함된다면 따옴표로 감싸주세요. ## generate -``` bash +```bash $ hexo generate ``` 정적 파일들을 생성합니다. -옵션 | 설명 ---- | --- -`-d`, `--deploy` | 생성이 종료된 후 deploy 합니다. -`-w`, `--watch` | 파일의 변경사항을 감시(watch)합니다. +| 옵션 | 설명 | +| ---------------- | ------------------------------------ | +| `-d`, `--deploy` | 생성이 종료된 후 deploy 합니다. | +| `-w`, `--watch` | 파일의 변경사항을 감시(watch)합니다. | ## publish -``` bash +```bash $ hexo publish [layout] <filename> ``` @@ -46,45 +46,45 @@ $ hexo publish [layout] <filename> ## server -``` bash +```bash $ hexo server ``` 로컬 서버를 구동시킵니다. 기본적으로 `http://localhost:4000/` 를 사용합니다. -옵션 | 설명 ---- | --- -`-p`, `--port` | 기본 포트를 덮어씁니다. -`-s`, `--static` | 정적인 파일만 구동합니다. -`-l`, `--log` | Logger를 활성화 시킵니다. Logger 형식을 덮어씁니다. +| 옵션 | 설명 | +| ---------------- | --------------------------------------------------- | +| `-p`, `--port` | 기본 포트를 덮어씁니다. | +| `-s`, `--static` | 정적인 파일만 구동합니다. | +| `-l`, `--log` | Logger를 활성화 시킵니다. Logger 형식을 덮어씁니다. | ## deploy -``` bash +```bash $ hexo deploy ``` 웹 사이트를 deploy 합니다. -옵션 | 설명 ---- | --- -`-g`, `--generate` | Deploy 하기 전에 generate를 수행합니다. +| 옵션 | 설명 | +| ------------------ | --------------------------------------- | +| `-g`, `--generate` | Deploy 하기 전에 generate를 수행합니다. | ## render -``` bash +```bash $ hexo render <file1> [file2] ... ``` 파일을 렌더링합니다. -옵션 | 설명 ---- | --- -`-o`, `--output` | Output destination +| 옵션 | 설명 | +| ---------------- | ------------------ | +| `-o`, `--output` | Output destination | ## migrate -``` bash +```bash $ hexo migrate <type> ``` @@ -92,7 +92,7 @@ $ hexo migrate <type> ## clean -``` bash +```bash $ hexo clean ``` @@ -100,7 +100,7 @@ $ hexo clean ## list -``` bash +```bash $ hexo list <type> ``` @@ -108,7 +108,7 @@ $ hexo list <type> ## version -``` bash +```bash $ hexo version ``` @@ -118,7 +118,7 @@ $ hexo version ### 안전 모드 -``` bash +```bash $ hexo --safe ``` @@ -126,7 +126,7 @@ $ hexo --safe ### 디버그 모드 -``` bash +```bash $ hexo --debug ``` @@ -134,7 +134,7 @@ $ hexo --debug ### Silent 모드 -``` bash +```bash $ hexo --silent ``` @@ -142,7 +142,7 @@ $ hexo --silent ### 설정 파일의 변경(customizing) -``` bash +```bash $ hexo --config custom.yml ``` @@ -150,7 +150,7 @@ $ hexo --config custom.yml ### Draft 포스트 표시 -``` bash +```bash $ hexo --draft ``` @@ -158,7 +158,7 @@ Draft 포스트를 보여줍니다(`source/_drafts` 폴더에 저장되어 있 ### 현재 작업 디렉토리의 변경(customizing) -``` bash +```bash $ hexo --cwd /path/to/cwd ``` diff --git a/source/ko/docs/configuration.md b/source/ko/docs/configuration.md index 734ffcccd6..a1a82947ad 100644 --- a/source/ko/docs/configuration.md +++ b/source/ko/docs/configuration.md @@ -1,31 +1,32 @@ --- title: Configuration --- + `_config.yml` 파일의 사이트 환경 설정을 수정할 수 있습니다. ### Site -설정 | 설명 ---- | --- -`title` | 웹 사이트의 제목 -`subtitle` | 웹 사이트의 부제 -`description` | 웹 사이트에 대한 설명 -`keywords` | The keywords of your website. Supports multiple values. -`author` | 작성자 이름 -`language` | 웹 사이트의 주 사용언어. [2-lettter ISO-639-1 code](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) 참조. 기본값은 `en`. -`timezone` | 웹 사이트에서 사용하는 timezone. Hexo는 기본적으로 PC의 시간값을 사용합니다. 사용 가능한 timezone의 종류는 [여기](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones)에서 확인할 수 있습니다. 다음과 같은 형식으로 사용하세요. `America/New_York`, `Japan`, `UTC`. +| 설정 | 설명 | +| ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `title` | 웹 사이트의 제목 | +| `subtitle` | 웹 사이트의 부제 | +| `description` | 웹 사이트에 대한 설명 | +| `keywords` | The keywords of your website. Supports multiple values. | +| `author` | 작성자 이름 | +| `language` | 웹 사이트의 주 사용언어. [2-lettter ISO-639-1 code](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) 참조. 기본값은 `en`. | +| `timezone` | 웹 사이트에서 사용하는 timezone. Hexo는 기본적으로 PC의 시간값을 사용합니다. 사용 가능한 timezone의 종류는 [여기](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones)에서 확인할 수 있습니다. 다음과 같은 형식으로 사용하세요. `America/New_York`, `Japan`, `UTC`. | ### URL -설정 | 설명 | 기본값 ---- | --- | --- -`url` | 웹 사이트의 URL, must starts with `http://` or `https://` | -`root` | 웹 사이트의 루트 디렉토리 | `url's pathname` -`permalink` | 게시글의 [permalink](permalinks.html) 형식 | `:year/:month/:day/:title/` -`permalink_defaults` | Permalink 각 부분(segment)의 기본값 | -`pretty_urls` | Rewrite the [`permalink`](variables.html) variables to pretty URLs | -`pretty_urls.trailing_index` | Trailing `index.html`, set to `false` to remove it | `true` -`pretty_urls.trailing_html` | Trailing `.html`, set to `false` to remove it (_does not apply to trailing `index.html`_) | `true` +| 설정 | 설명 | 기본값 | +| ---------------------------- | ----------------------------------------------------------------------------------------- | --------------------------- | +| `url` | 웹 사이트의 URL, must starts with `http://` or `https://` | +| `root` | 웹 사이트의 루트 디렉토리 | `url's pathname` | +| `permalink` | 게시글의 [permalink](permalinks.html) 형식 | `:year/:month/:day/:title/` | +| `permalink_defaults` | Permalink 각 부분(segment)의 기본값 | +| `pretty_urls` | Rewrite the [`permalink`](variables.html) variables to pretty URLs | +| `pretty_urls.trailing_index` | Trailing `index.html`, set to `false` to remove it | `true` | +| `pretty_urls.trailing_html` | Trailing `.html`, set to `false` to remove it (_does not apply to trailing `index.html`_) | `true` | {% note info Website in subdirectory %} 당신의 웹 사이트가 `http://example.org/blog`와 같이 서브디렉토리에 있다면 `url`은 `http://example.org/blog`고 설정하고 `root`는 `/blog/`로 설정하세요. @@ -33,53 +34,53 @@ title: Configuration ### Directory -설정 | 설명 | 기본값 ---- | --- | --- -`source_dir` | 컨텐츠들이 저장되어 있는 소스 폴더 | `source` -`public_dir` | 생성된 정적 사이트들이 저장될 공용 폴더 | `public` -`tag_dir` | 태그 디렉토리 | `tags` -`archive_dir` | 저장소 디렉토리 | `archives` -`category_dir` | 카테고리 디렉토리 | `categories` -`code_dir` | Code 디렉토리 | `downloads/code` -`i18n_dir` | i18n 디렉토리 | `:lang` -`skip_render` | 렌더링하지 않을 경로. 경로 매칭을 위해 [glob expressions](https://github.com/micromatch/micromatch#extended-globbing)를 사용할 수 있습니다. | +| 설정 | 설명 | 기본값 | +| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | ---------------- | +| `source_dir` | 컨텐츠들이 저장되어 있는 소스 폴더 | `source` | +| `public_dir` | 생성된 정적 사이트들이 저장될 공용 폴더 | `public` | +| `tag_dir` | 태그 디렉토리 | `tags` | +| `archive_dir` | 저장소 디렉토리 | `archives` | +| `category_dir` | 카테고리 디렉토리 | `categories` | +| `code_dir` | Code 디렉토리 | `downloads/code` | +| `i18n_dir` | i18n 디렉토리 | `:lang` | +| `skip_render` | 렌더링하지 않을 경로. 경로 매칭을 위해 [glob expressions](https://github.com/micromatch/micromatch#extended-globbing)를 사용할 수 있습니다. | ### Writing -설정 | 설명 | 기본값 ---- | --- | --- -`new_post_name` | 새 포스트의 파일명 형식 | `:title.md` -`default_layout` | 기본 레이아웃 | `post` -`titlecase` | 제목을 제목에 맞는 대/소문자로 변경할 것인지 선택 | `false` -`external_link` | 외부 링크를 새 탭에서 열 것인지 선택 -`external_link.enable` | 외부 링크를 새 탭에서 열 것인지 선택 | `true` -`external_link.field` | Applies to the whole `site` or `post` only | `site` -`external_link.exclude` | Exclude hostname. Specify subdomain when applicable, including `www` | `[]` -`filename_case` | 파일명을 소문자(`1`) 또는 대문자(`2`)로 변경 | `0` -`render_drafts` | Draft 문서를 표시할 것인지 선택 | `false` -`post_asset_folder` | [Asset 폴더](asset-folders.html)를 활성화 할 것인지 선택 | `false` -`relative_link` | 루트 폴더에 대한 상대 경로로 링크를 만들 것인지 선택 | `false` -`future` | 미래의 포스트를 표시할 것인지 선택 | `true` -`highlight` | Code block의 설정, see [Highlight.js](/docs/syntax-highlight#Highlight-js) section for usage guide | -`prismjs` | Code block의 설정, see [PrismJS](/docs/syntax-highlight#PrismJS) section for usage guide | +| 설정 | 설명 | 기본값 | +| ----------------------- | -------------------------------------------------------------------------------------------------- | ----------- | +| `new_post_name` | 새 포스트의 파일명 형식 | `:title.md` | +| `default_layout` | 기본 레이아웃 | `post` | +| `titlecase` | 제목을 제목에 맞는 대/소문자로 변경할 것인지 선택 | `false` | +| `external_link` | 외부 링크를 새 탭에서 열 것인지 선택 | +| `external_link.enable` | 외부 링크를 새 탭에서 열 것인지 선택 | `true` | +| `external_link.field` | Applies to the whole `site` or `post` only | `site` | +| `external_link.exclude` | Exclude hostname. Specify subdomain when applicable, including `www` | `[]` | +| `filename_case` | 파일명을 소문자(`1`) 또는 대문자(`2`)로 변경 | `0` | +| `render_drafts` | Draft 문서를 표시할 것인지 선택 | `false` | +| `post_asset_folder` | [Asset 폴더](asset-folders.html)를 활성화 할 것인지 선택 | `false` | +| `relative_link` | 루트 폴더에 대한 상대 경로로 링크를 만들 것인지 선택 | `false` | +| `future` | 미래의 포스트를 표시할 것인지 선택 | `true` | +| `highlight` | Code block의 설정, see [Highlight.js](/docs/syntax-highlight#Highlight-js) section for usage guide | +| `prismjs` | Code block의 설정, see [PrismJS](/docs/syntax-highlight#PrismJS) section for usage guide | ### Category & Tag -설정 | 설명 | 기본값 ---- | --- | --- -`default_category` | 기본 분류 | `uncategorized` -`category_map` | 분류 목록 | -`tag_map` | 태그 목록 | +| 설정 | 설명 | 기본값 | +| ------------------ | --------- | --------------- | +| `default_category` | 기본 분류 | `uncategorized` | +| `category_map` | 분류 목록 | +| `tag_map` | 태그 목록 | ### Date / Time format Hexo는 날짜 처리 시 [Moment.js](http://momentjs.com/)를 사용합니다. -설정 | 설명 | 기본값 ---- | --- | --- -`date_format` | 날짜 형식 | `YYYY-MM-DD` -`time_format` | 시간 형식 | `HH:mm:ss` -`updated_option` | The [`updated`](/ko/docs/variables#페이지 변수) value to used when not provided in the front-matter | `mtime` +| 설정 | 설명 | 기본값 | +| ---------------- | --------------------------------------------------------------------------------------------------- | ------------ | +| `date_format` | 날짜 형식 | `YYYY-MM-DD` | +| `time_format` | 시간 형식 | `HH:mm:ss` | +| `updated_option` | The [`updated`](/ko/docs/variables#페이지 변수) value to used when not provided in the front-matter | `mtime` | {% note info updated_option %} `updated_option` controls the `updated` value when not provided in the front-matter: @@ -93,18 +94,18 @@ Hexo는 날짜 처리 시 [Moment.js](http://momentjs.com/)를 사용합니다. ### Pagination -설정 | 설명 | 기본값 ---- | --- | --- -`per_page` | 하나의 페이지에 표시할 포스트의 개수. `0`이면 pagination을 표시하지 않습니다. | `10` -`pagination_dir` | Pagination 디렉토리 | `page` +| 설정 | 설명 | 기본값 | +| ---------------- | ----------------------------------------------------------------------------- | ------ | +| `per_page` | 하나의 페이지에 표시할 포스트의 개수. `0`이면 pagination을 표시하지 않습니다. | `10` | +| `pagination_dir` | Pagination 디렉토리 | `page` | ### Extensions -설정 | 설명 ---- | --- -`theme` | 테마명. `false`라면 테마를 끕니다. -`deploy` | Deployment 설정 -`meta_generator` | [Meta generator](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta#Attributes) tag. `false` disables injection of the tag. +| 설정 | 설명 | +| ---------------- | --------------------------------------------------------------------------------------------------------------------------------------- | +| `theme` | 테마명. `false`라면 테마를 끕니다. | +| `deploy` | Deployment 설정 | +| `meta_generator` | [Meta generator](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta#Attributes) tag. `false` disables injection of the tag. | ### Include/Exclude Files or Folders @@ -112,11 +113,11 @@ Use the following options to explicitly process or ignore certain files/folders. `include` and `exclude` options only apply to the `source/` folder, whereas `ignore` option applies to all folders. -Setting | Description ---- | --- -`include` | Include hidden files (including files/folders with a name that start with an underscore, with an exception*) -`exclude` | Exclude files/folders -`ignore` | Ignore files/folders +| Setting | Description | +| --------- | ------------------------------------------------------------------------------------------------------------- | +| `include` | Include hidden files (including files/folders with a name that start with an underscore, with an exception\*) | +| `exclude` | Exclude files/folders | +| `ignore` | Ignore files/folders | Examples: @@ -165,7 +166,7 @@ Each value in the list must be enclosed with single/double quotes. A custom config file path can be specified by adding the `--config` flag to your `hexo` commands with a path to an alternate YAML or JSON config file, or a comma-separated list (no spaces) of multiple YAML or JSON files. -``` bash +```bash # use 'custom.yml' in place of '_config.yml' $ hexo server --config custom.yml @@ -193,7 +194,7 @@ theme: "my-theme" theme_config: bio: "My awesome bio" foo: - bar: 'a' + bar: "a" ``` ```yml @@ -208,11 +209,11 @@ Resulting in theme configuration: ```json { - bio: "My awesome bio", - logo: "a-cool-image.png", - foo: { - bar: "a", - baz: "b" + "bio": "My awesome bio", + "logo": "a-cool-image.png", + "foo": { + "bar": "a", + "baz": "b" } } ``` @@ -232,7 +233,7 @@ theme: "my-theme" # _config.my-theme.yml bio: "My awesome bio" foo: - bar: 'a' + bar: "a" ``` ```yml @@ -247,11 +248,11 @@ Resulting in theme configuration: ```json { - bio: "My awesome bio", - logo: "a-cool-image.png", - foo: { - bar: "a", - baz: "b" + "bio": "My awesome bio", + "logo": "a-cool-image.png", + "foo": { + "bar": "a", + "baz": "b" } } ``` diff --git a/source/ko/docs/contributing.md b/source/ko/docs/contributing.md index 5482f3e8a0..56921c6e4f 100644 --- a/source/ko/docs/contributing.md +++ b/source/ko/docs/contributing.md @@ -25,7 +25,7 @@ Also, Hexo has its own [ESLint config](https://github.com/hexojs/eslint-config-h 1. Fork [hexojs/hexo]. 2. 저장소를 당신의 컴퓨터에 clone하고 의존 사항들을 설치합니다. -``` bash +```bash $ git clone https://github.com/<username>/hexo.git $ cd hexo $ npm install @@ -34,7 +34,7 @@ $ git submodule update --init 3. 기능 branch를 생성합니다. -``` bash +```bash $ git checkout -b new_feature ``` @@ -52,7 +52,7 @@ $ git push origin new_feature - `package.json`의 version number는 수정하지 마세요. - 당신의 Pull request는 테스트를 통과했을 때에만 merge됩니다. 반영하기 전에 test를 돌려보세요. -``` bash +```bash $ npm test ``` @@ -69,7 +69,7 @@ Hexo 문서는 opensource이며 [hexojs/site]에서 소스 코드를 검색할 1. Fork [hexojs/site] 2. 저장소를 당신의 컴퓨터에 clone하고 의존 사항들을 설치합니다. -``` bash +```bash $ npm install hexo-cli -g # If you don't have hexo-cli installed $ git clone https://github.com/<username>/site.git $ cd site @@ -78,7 +78,7 @@ $ npm install 3. 문서를 수정하세요. Server를 돌려서 실시간으로 확인할 수 있습니다. -``` bash +```bash $ hexo server ``` diff --git a/source/ko/docs/data-files.md b/source/ko/docs/data-files.md index ced274ad21..f16c4a290d 100644 --- a/source/ko/docs/data-files.md +++ b/source/ko/docs/data-files.md @@ -1,11 +1,12 @@ --- title: Data Files --- + 포스트 내에서 직접 호출하여 사용이 불가능한 데이터나 다른 장소에서 사용한 데이터를 당신의 템플릿에서 재사용하고 싶을 때를 위하여 Hexo 3에서는 새로운 **Data files** 을 제공합니다. 이 기능은 `source/_data` 폴더의 YAML 또는 JSON 파일을 불러와서 사용할 수 있게 만들어줍니다. 아래의 예시에서 `source/_data`폴더에 `menu.yml`을 추가합니다. -``` yaml +```yaml Home: / Gallery: /gallery/ Archives: /archives/ diff --git a/source/ko/docs/front-matter.md b/source/ko/docs/front-matter.md index 212fa909c9..cf8b1444f8 100644 --- a/source/ko/docs/front-matter.md +++ b/source/ko/docs/front-matter.md @@ -1,11 +1,12 @@ --- title: Front-matter --- + Front-matter는 파일 시작 시 작성하는 YAML 또는 JSON 구역입니다. 게시물에 대한 환경 설정을 이 곳에서 합니다. Front-matter가 끝나는 부분은 YAML의 경우 세 개의 대시(-) 로, JSON의 경우 세 개의 세미콜론(;)을 넣어서 구분합니다. **YAML** -``` yaml +```yaml --- title: Hello World date: 2013/7/13 20:46:25 @@ -14,7 +15,7 @@ date: 2013/7/13 20:46:25 **JSON** -``` json +```json "title": "Hello World", "date": "2013/7/13 20:46:25" ;;; @@ -22,23 +23,23 @@ date: 2013/7/13 20:46:25 ### 환경설정 및 기본 값 -설정 | 설명 | 기본 값 ---- | --- | --- -`layout` | 레이아웃 | [`config.default_layout`](/ko/docs/configuration#Writing) -`title` | 타이틀 | Filename (posts only) -`date` | 발행일 | 파일이 생성된 날짜 -`updated` | 갱신일 | 파일이 업로드된 날짜 -`comments` | 포스트에서 comment 기능을 사용할지 여부 | true -`tags` | 태그 (page에서는 사용 불가능) | -`categories` | 카테고리 (page에서는 사용 불가능) | -`permalink` | 포스트의 기본 permalink를 override합니다. | -`excerpt` | Page excerpt in plain text. Use [this plugin](/docs/tag-plugins#Post-Excerpt) to format the text | -`disableNunjucks` | Disable rendering of Nunjucks tag `{{ }}`/`{% %}` and [tag plugins](/docs/tag-plugins) when enabled -`lang` | Set the language to override [auto-detection](/docs/internationalization#Path) | Inherited from `_config.yml` +| 설정 | 설명 | 기본 값 | +| ----------------- | --------------------------------------------------------------------------------------------------- | --------------------------------------------------------- | +| `layout` | 레이아웃 | [`config.default_layout`](/ko/docs/configuration#Writing) | +| `title` | 타이틀 | Filename (posts only) | +| `date` | 발행일 | 파일이 생성된 날짜 | +| `updated` | 갱신일 | 파일이 업로드된 날짜 | +| `comments` | 포스트에서 comment 기능을 사용할지 여부 | true | +| `tags` | 태그 (page에서는 사용 불가능) | +| `categories` | 카테고리 (page에서는 사용 불가능) | +| `permalink` | 포스트의 기본 permalink를 override합니다. | +| `excerpt` | Page excerpt in plain text. Use [this plugin](/docs/tag-plugins#Post-Excerpt) to format the text | +| `disableNunjucks` | Disable rendering of Nunjucks tag `{{ }}`/`{% %}` and [tag plugins](/docs/tag-plugins) when enabled | +| `lang` | Set the language to override [auto-detection](/docs/internationalization#Path) | Inherited from `_config.yml` | #### 레이아웃 -The default layout is `post`, in accordance to the value of [`default_layout`]((/docs/configuration#Writing)) setting in `_config.yml`. When the layout is disabled (`layout: false`) in an article, it will not be processed with a theme. However, it will still be rendered by any available renderer: if an article is written in Markdown and a Markdown renderer (like the default [hexo-renderer-marked](https://github.com/hexojs/hexo-renderer-marked)) is installed, it will be rendered to HTML. +The default layout is `post`, in accordance to the value of [`default_layout`](/docs/configuration#Writing) setting in `_config.yml`. When the layout is disabled (`layout: false`) in an article, it will not be processed with a theme. However, it will still be rendered by any available renderer: if an article is written in Markdown and a Markdown renderer (like the default [hexo-renderer-marked](https://github.com/hexojs/hexo-renderer-marked)) is installed, it will be rendered to HTML. [Tag plugins](/docs/tag-plugins) are always processed regardless of layout, unless disabled by the `disableNunjucks` setting or [renderer](/api/renderer#Disable-Nunjucks-tags). @@ -48,12 +49,12 @@ The default layout is `post`, in accordance to the value of [`default_layout`](( **Example** -``` yaml +```yaml categories: -- Sports -- Baseball + - Sports + - Baseball tags: -- Injury -- Fight -- Shocking + - Injury + - Fight + - Shocking ``` diff --git a/source/ko/docs/generating.md b/source/ko/docs/generating.md index a4f08915c6..fdb3d0ed45 100644 --- a/source/ko/docs/generating.md +++ b/source/ko/docs/generating.md @@ -1,9 +1,10 @@ --- title: Generating --- + Hexo를 사용하여 매우 쉽고 빠르게 정적인 파일을 생성할 수 있습니다. -``` bash +```bash $ hexo generate ``` @@ -11,7 +12,7 @@ $ hexo generate Hexo는 파일이 변경되거나 새로 생성되는 경우 쉽게 알아챌 수 있습니다. Hexo는 SHA1 checksum을 비교하여 파일의 변경을 확인합니다. -``` bash +```bash $ hexo generate --watch ``` @@ -19,7 +20,7 @@ $ hexo generate --watch 생성 후에 deploy 하기위해 다음 명령어 중 하나를 실행해야 합니다. 두 명령어는 동일한 동작을 수행합니다. -``` bash +```bash $ hexo generate --deploy $ hexo deploy --generate ``` diff --git a/source/ko/docs/github-pages.md b/source/ko/docs/github-pages.md index ec52a841e0..68a109dbea 100755 --- a/source/ko/docs/github-pages.md +++ b/source/ko/docs/github-pages.md @@ -4,14 +4,14 @@ title: GitHub Pages In this tutorial, we use [Travis CI](https://travis-ci.com/) to deploy Github Pages. It is free for open source repository, meaning your repository's `master` branch has to be public. Please skip to the [Private repository](#Private-repository) section if you prefer to keep the repo private, or prefer not to upload your source folder to GitHub. -1. Create a repo named <b>*username*.github.io</b>, where username is your username on GitHub. If you have already uploaded to other repo, rename the repo instead. +1. Create a repo named <b>_username_.github.io</b>, where username is your username on GitHub. If you have already uploaded to other repo, rename the repo instead. 2. Push the files of your Hexo folder to the repository. The `public/` folder is not (and should not be) uploaded by default, make sure the `.gitignore` file contains `public/` line. The folder structure should be roughly similar to [this repo](https://github.com/hexojs/hexo-starter), without the `.gitmodules` file. 3. Add [Travis CI](https://github.com/marketplace/travis-ci) to your account. 4. Go to [Applications settings](https://github.com/settings/installations), configure Travis CI to have access to the repo. 5. You'll be redirected to Travis page. 6. On a new tab, generate a [new token](https://github.com/settings/tokens) with **repo** scopes. Note down the token value. 7. On the Travis page, go to your repo's setting. Under **Environment Variables**, put **GH_TOKEN** as name and paste the token onto value. Click Add to save it. -8. Add `.travis.yml` file to your repo (alongside _config.yml & package.json) with the following content: +8. Add `.travis.yml` file to your repo (alongside \_config.yml & package.json) with the following content: ```yml sudo: false @@ -36,14 +36,14 @@ deploy: 9. Once Travis CI finish the deployment, the generated pages can be found in the `gh-pages` branch of your repository 10. In your GitHub repo's setting, navigate to "GitHub Pages" section and change Source to **gh-pages branch**. -11. Check the webpage at *username*.github.io. +11. Check the webpage at _username_.github.io. ## Project page If you prefer to have a project page on GitHub: -1. Navigate to your repo on GitHub. Go to the **Settings** tab. Change the **Repository name** so your blog is available at <b>username.github.io/*repository*</b>, **repository** can be any name, like *blog* or *hexo*. -2. Edit your **_config.yml**, change the `root:` value to the `/<repository>/` (must starts and ends with a slash, without the brackets). +1. Navigate to your repo on GitHub. Go to the **Settings** tab. Change the **Repository name** so your blog is available at <b>username.github.io/_repository_</b>, **repository** can be any name, like _blog_ or _hexo_. +2. Edit your **\_config.yml**, change the `root:` value to the `/<repository>/` (must starts and ends with a slash, without the brackets). 3. Commit and push. ## Private repository @@ -51,18 +51,18 @@ If you prefer to have a project page on GitHub: The following instruction is adapted from [one-command deployment](/docs/one-command-deployment) page. 1. Install [hexo-deployer-git](https://github.com/hexojs/hexo-deployer-git). -2. Add the following configurations to **_config.yml**, (remove existing lines if any) +2. Add the following configurations to **\_config.yml**, (remove existing lines if any) - ``` yml - deploy: - type: git - repo: https://github.com/<username>/<project> - # example, https://github.com/hexojs/hexojs.github.io - branch: gh-pages - ``` +```yml +deploy: + type: git + repo: https://github.com/<username>/<project> + # example, https://github.com/hexojs/hexojs.github.io + branch: gh-pages +``` 3. Run `hexo clean && hexo deploy`. -4. Check the webpage at *username*.github.io. +4. Check the webpage at _username_.github.io. ## Useful links diff --git a/source/ko/docs/gitlab-pages.md b/source/ko/docs/gitlab-pages.md index 7b5ce4d6c9..2d4384d923 100644 --- a/source/ko/docs/gitlab-pages.md +++ b/source/ko/docs/gitlab-pages.md @@ -2,12 +2,12 @@ title: GitLab Pages --- -1. Create a new repository named <b>*username*.gitlab.io</b>, where username is your username on GitLab. If you have already uploaded to other repo, rename the repo instead. +1. Create a new repository named <b>_username_.gitlab.io</b>, where username is your username on GitLab. If you have already uploaded to other repo, rename the repo instead. 2. Enable Shared Runners via `Settings -> CI / CD -> Shared Runners`. 3. Push the files of your Hexo folder to the repository. The `public/` folder is not (and should not be) uploaded by default, make sure the `.gitignore` file contains `public/` line. The folder structure should be roughly similar to [this repo](https://gitlab.com/pages/hexo). -4. Add `.gitlab-ci.yml` file to your repo (alongside _config.yml & package.json) with the following content: +4. Add `.gitlab-ci.yml` file to your repo (alongside \_config.yml & package.json) with the following content: -``` yml +```yml image: node:10-alpine # use nodejs v10 LTS cache: paths: @@ -27,15 +27,15 @@ pages: - master ``` -5. *username*.gitlab.io should be up and running, once GitLab CI finishes the deployment job, +5. _username_.gitlab.io should be up and running, once GitLab CI finishes the deployment job, 6. (Optional) If you wish to inspect the generated site assets (html, css, js, etc), they can be found in the [job artifact](https://docs.gitlab.com/ee/user/project/pipelines/job_artifacts.html). ## Project page If you prefer to have a project page on GitLab: -1. Go to `Settings -> General -> Advanced -> Change path`. Change the value to a name, so the website is available at <b>username.gitlab.io/*name*</b>. It can be any name, like *blog* or *hexo*. -2. Edit **_config.yml**, change the `root:` value from `""` to `"name"`. +1. Go to `Settings -> General -> Advanced -> Change path`. Change the value to a name, so the website is available at <b>username.gitlab.io/_name_</b>. It can be any name, like _blog_ or _hexo_. +2. Edit **\_config.yml**, change the `root:` value from `""` to `"name"`. 3. Commit and push. ## Useful links diff --git a/source/ko/docs/helpers.md b/source/ko/docs/helpers.md index 96941504a5..9080542784 100644 --- a/source/ko/docs/helpers.md +++ b/source/ko/docs/helpers.md @@ -1,6 +1,7 @@ --- title: Helpers --- + Helper는 템플릿에 정보(snippet)를 쉽게 삽입할 수 있도록 도와줍니다. 소스 파일에서는 Helper를 사용할 수 없습니다. ## URL @@ -9,7 +10,7 @@ Helper는 템플릿에 정보(snippet)를 쉽게 삽입할 수 있도록 도와 루트 경로를 포함한 url을 반환합니다. Hexo 2.7부터 `config.root + path` 대신 이 helper를 사용할 수 있습니다. -``` js +```js <%- url_for(path) %> ``` @@ -17,7 +18,7 @@ Helper는 템플릿에 정보(snippet)를 쉽게 삽입할 수 있도록 도와 `from`부터 `to`까지의 상대 경로를 반환합니다. -``` js +```js <%- relative_url(from, to) %> ``` @@ -26,13 +27,13 @@ Helper는 템플릿에 정보(snippet)를 쉽게 삽입할 수 있도록 도와 Gravatar 이미지를 삽입합니다. [options] 파라미터를 지정하지 않은 경우, 기본 값이 적용됩니다. [options] 파라미터를 지정할 경우 숫자로 크기를 지정하여 Gravatar에 전달할 수 있습니다. 또 다른 방법으로, object를 설정할 경우 Gravatar를 위한 query string으로 변환됩니다. -``` js +```js <%- gravatar(email, [options]) %> ``` **예시:** -``` js +```js <%- gravatar('a@abc.com') %> // https://www.gravatar.com/avatar/b9b00e66c6b8a70f88c73cb6bdb06787 @@ -49,13 +50,13 @@ Gravatar 이미지를 삽입합니다. CSS 파일들을 불러옵니다. `path`에는 문자열(string) 또는 배열(array)을 사용할 수 있습니다. 만약 `path`가 `/` 또는 프로토콜명으로 시작하지 않는다면, 루트 URL이 접두어로 붙습니다. `path` 뒤에 `.css` 파일을 기입하지 않으면 자동으로 추가합니다. Use object type for custom attributes. -``` js +```js <%- css(path, ...) %> ``` **예시:** -``` js +```js <%- css('style.css') %> // <link rel="stylesheet" href="/style.css"> @@ -75,13 +76,13 @@ CSS 파일들을 불러옵니다. `path`에는 문자열(string) 또는 배열(a JavaScript 파일들을 불러옵니다. `path`에는 문자열(string) 또는 배열(array)을 사용할 수 있습니다. 만약 `path`가 `/` 또는 프로토콜명으로 시작하지 않는다면, 루트 URL이 접두어로 붙습니다. `path` 뒤에 `.js` 파일을 기입하지 않으면 자동으로 추가합니다. Use object type for custom attributes. -``` js +```js <%- js(path, ...) %> ``` **예시:** -``` js +```js <%- js('script.js') %> // <script src="/script.js"></script> @@ -101,19 +102,19 @@ JavaScript 파일들을 불러옵니다. `path`에는 문자열(string) 또는 링크를 삽입합니다. -``` js +```js <%- link_to(path, [text], [options]) %> ``` -옵션 | 설명 | 기본 값 ---- | --- | --- -`external` | 링크를 새 탭에 엽니다. | false -`class` | Class명 | -`id` | ID | +| 옵션 | 설명 | 기본 값 | +| ---------- | ---------------------- | ------- | +| `external` | 링크를 새 탭에 엽니다. | false | +| `class` | Class명 | +| `id` | ID | **예시:** -``` js +```js <%- link_to('http://www.google.com') %> // <a href="http://www.google.com" title="http://www.google.com">http://www.google.com</a> @@ -128,22 +129,22 @@ JavaScript 파일들을 불러옵니다. `path`에는 문자열(string) 또는 메일 링크를 삽입합니다. -``` js +```js <%- mail_to(path, [text], [options]) %> ``` -옵션 | 설명 ---- | --- -`class` | Class명 -`id` | ID -`subject` | 메일 제목 -`cc` | 참조 -`bcc` | 비밀참조 -`body` | 메일 내용 +| 옵션 | 설명 | +| --------- | --------- | +| `class` | Class명 | +| `id` | ID | +| `subject` | 메일 제목 | +| `cc` | 참조 | +| `bcc` | 비밀참조 | +| `body` | 메일 내용 | **예시:** -``` js +```js <%- mail_to('a@abc.com') %> // <a href="mailto:a@abc.com" title="a@abc.com">a@abc.com</a> @@ -155,23 +156,23 @@ JavaScript 파일들을 불러옵니다. `path`에는 문자열(string) 또는 이미지를 삽입합니다. -``` js +```js <%- image_tag(path, [options]) %> ``` -옵션 | 설명 ---- | --- -`alt` | 이미지 대신 표시할 텍스트 -`class` | Class명 -`id` | ID -`width` | 이미지의 가로 크기 -`height` | 이미지의 세로 크기 +| 옵션 | 설명 | +| -------- | ------------------------- | +| `alt` | 이미지 대신 표시할 텍스트 | +| `class` | Class명 | +| `id` | ID | +| `width` | 이미지의 가로 크기 | +| `height` | 이미지의 세로 크기 | ### favicon_tag 파비콘을 삽입합니다. -``` js +```js <%- favicon_tag(path) %> ``` @@ -179,18 +180,18 @@ JavaScript 파일들을 불러옵니다. `path`에는 문자열(string) 또는 Feed 링크를 삽입합니다. -``` js +```js <%- feed_tag(path, [options]) %> ``` -옵션 | 설명 | 기본 값 ---- | --- | --- -`title` | Feed 제목 | `config.title` -`type` | Feed 형식 | +| 옵션 | 설명 | 기본 값 | +| ------- | --------- | -------------- | +| `title` | Feed 제목 | `config.title` | +| `type` | Feed 형식 | **Examples:** -``` js +```js <%- feed_tag('atom.xml') %> // <link rel="alternate" href="/atom.xml" title="Hexo" type="application/atom+xml"> @@ -208,7 +209,7 @@ Feed 링크를 삽입합니다. `path`가 현재 페이지의 URL과 동일한지 체크합니다. `strict` 옵션을 사용하면 제한적인 매칭을 활성화 합니다. -``` js +```js <%- is_current(path, [strict]) %> ``` @@ -216,7 +217,7 @@ Feed 링크를 삽입합니다. 현재 페이지가 home 페이지인지 체크합니다. -``` js +```js <%- is_home() %> ``` @@ -224,7 +225,7 @@ Feed 링크를 삽입합니다. 현재 페이지가 포스트인지 체크합니다. -``` js +```js <%- is_post() %> ``` @@ -232,7 +233,7 @@ Feed 링크를 삽입합니다. 현재 페이지가 아카이브 페이지인지 체크합니다. -``` js +```js <%- is_archive() %> ``` @@ -240,7 +241,7 @@ Feed 링크를 삽입합니다. 현재 페이지가 연간 아카이브 페이지인지 체크합니다. -``` js +```js <%- is_year() %> ``` @@ -248,7 +249,7 @@ Feed 링크를 삽입합니다. 현재 페이지가 월간 아카이브 페이지인지 체크합니다. -``` js +```js <%- is_month() %> ``` @@ -257,7 +258,7 @@ Feed 링크를 삽입합니다. 현재 페이지가 카테고리 페이지인지 체크합니다. 파라미터에 문자열을 넣으면, 현재 페이지가 해당 문자열의 카테고리에 속해있는지 체크합니다. -``` js +```js <%- is_category() %> <%- is_category('hobby') %> ``` @@ -267,7 +268,7 @@ Feed 링크를 삽입합니다. 현재 페이지가 태그 페이지인지 체크합니다. 파라미터에 문자열을 넣으면, 현재 페이지가 해당 문자열의 태그에 속해있는지 체크합니다. -``` js +```js <%- is_tag() %> <%- is_tag('hobby') %> ``` @@ -278,7 +279,7 @@ Feed 링크를 삽입합니다. 문자열에서 공백을 제거합니다. -``` js +```js <%- trim(string) %> ``` @@ -286,13 +287,13 @@ Feed 링크를 삽입합니다. 문자열에서 모든 HTML 태그를 제거합니다. -``` js +```js <%- strip_html(string) %> ``` **예시:** -``` js +```js <%- strip_html('It\'s not <b>important</b> anymore!') %> // It's not important anymore! ``` @@ -301,13 +302,13 @@ Feed 링크를 삽입합니다. 문자열을 적절한 타이틀 케이스(소문자/대문자)에 맞게 변환합니다. -``` js +```js <%- titlecase(string) %> ``` **예시:** -``` js +```js <%- titlecase('this is an apple') %> # This is an Apple ``` @@ -316,13 +317,13 @@ Feed 링크를 삽입합니다. Markdown에 맞게 문자열을 렌더링합니다. -``` js +```js <%- markdown(str) %> ``` **예시:** -``` js +```js <%- markdown('make me **strong**') %> // make me <strong>strong</strong> ``` @@ -331,13 +332,13 @@ Markdown에 맞게 문자열을 렌더링합니다. 문자열을 렌더링합니다. -``` js +```js <%- render(str, engine, [options]) %> ``` **Examples:** -``` js +```js <%- render('p(class="example") Test', 'pug'); %> // <p class="example">Test</p> ``` @@ -348,13 +349,13 @@ See [Rendering](https://hexo.io/ko/api/rendering) for more details. 주어진 `length`에 맞게 문자열을 포장합니다. `length`의 기본값은 80 입니다. -``` js +```js <%- word_wrap(str, [length]) %> ``` **예시:** -``` js +```js <%- word_wrap('Once upon a time', 8) %> // Once upon\n a time ``` @@ -363,13 +364,13 @@ See [Rendering](https://hexo.io/ko/api/rendering) for more details. `length` 이후의 문자들을 잘라냅니다. 기본 값은 30 입니다. -``` js +```js <%- truncate(text, [options]) %> ``` **예시:** -``` js +```js <%- truncate('Once upon a time in a world far far away', {length: 17}) %> // Once upon a ti... @@ -384,13 +385,13 @@ See [Rendering](https://hexo.io/ko/api/rendering) for more details. Escapes HTML entities in a string. -``` js +```js <%- escape_html(str) %> ``` **Examples:** -``` js +```js <%- escape_html('<p>Hello "world".</p>') %> // <p>Hello "world".</p> ``` @@ -401,26 +402,26 @@ Escapes HTML entities in a string. 다른 템플릿 파일을 불러옵니다. 지역 변수인 `locals`에 정의할 수 있습니다. -``` js +```js <%- partial(layout, [locals], [options]) %> ``` -옵션 | 설명 | 기본 값 ---- | --- | --- -`cache` | 내용을 캐싱합니다. (Fragment cache 사용) | `false` -`only` | 지역 변수에 한정합니다. 템플릿에서 `locals` 변수만 설정할 수 있습니다. | `false` +| 옵션 | 설명 | 기본 값 | +| ------- | ---------------------------------------------------------------------- | ------- | +| `cache` | 내용을 캐싱합니다. (Fragment cache 사용) | `false` | +| `only` | 지역 변수에 한정합니다. 템플릿에서 `locals` 변수만 설정할 수 있습니다. | `false` | ### fragment_cache Fragment에 컨텐츠를 캐싱합니다. 컨텐츠를 fragment단위로 저장하고 다음 요청이 들어오면 캐시를 제공합니다. -``` js +```js <%- fragment_cache(id, fn); ``` **예시:** -``` js +```js <%- fragment_cache('header', function(){ return '<header></header>'; }) %> @@ -432,13 +433,13 @@ Fragment에 컨텐츠를 캐싱합니다. 컨텐츠를 fragment단위로 저장 형식이 정의된 날짜를 삽입합니다. `date`는 unix time, ISO string, date object, [Moment.js] 객체를 사용할 수 있습니다. `format`은 기본 값으로 정의된 `date_format`를 사용합니다. -``` js +```js <%- date(date, [format]) %> ``` **예시:** -``` js +```js <%- date(Date.now()) %> // 2013-01-01 @@ -450,13 +451,13 @@ Fragment에 컨텐츠를 캐싱합니다. 컨텐츠를 fragment단위로 저장 XML 형식의 날짜를 삽입합니다. `date`는 unix time, ISO string, date object, [Moment.js] 객체를 사용할 수 있습니다. -``` js +```js <%- date_xml(date) %> ``` **예시:** -``` js +```js <%- date_xml(Date.now()) %> // 2013-01-01T00:00:00.000Z ``` @@ -465,13 +466,13 @@ XML 형식의 날짜를 삽입합니다. `date`는 unix time, ISO string, date o 형식이 정의된 시간을 사입합니다. `date`는 unix time, ISO string, date object, [Moment.js] 객체를 사용할 수 있습니다. `format`은 기본 값으로 정의된 `time_format`를 사용합니다. -``` js +```js <%- time(date, [format]) %> ``` **예시:** -``` js +```js <%- time(Date.now()) %> // 13:05:12 @@ -483,13 +484,13 @@ XML 형식의 날짜를 삽입합니다. `date`는 unix time, ISO string, date o 형식이 정의된 날짜와 시간을 삽입합니다. `date`는 unix time, ISO string, date object, [Moment.js] 객체를 사용할 수 있습니다. `format`은 기본 값으로 정의된 `date_format + time_format`를 사용합니다. -``` js +```js <%- full_date(date, [format]) %> ``` **예시:** -``` js +```js <%- full_date(new Date()) %> // Jan 1, 2013 0:00:00 @@ -507,51 +508,51 @@ XML 형식의 날짜를 삽입합니다. `date`는 unix time, ISO string, date o 모든 카테고리의 목록을 삽입합니다. -``` js +```js <%- list_categories([options]) %> ``` -옵션 | 설명 | 기본 값 ---- | --- | --- -`orderby` | 카테고리 정렬 기준 | name -`order` | 정렬 방식. `1`, `asc`은 오름차순; `-1`, `desc`은 내림차순 | 1 -`show_count` | 각 카테고리 별 포스트의 번호를 표시합니다. | true -`style` | 카테고리 목록 표시의 스타일. `list`는 카테고리 목록을 순서없이 표시합니다. | list -`separator` | 카테고리 별 구분자. (`style`이 `list`가 아닐 때만 동작합니다.) | , -`depth` | 카테고리의 계층을 표시합니다. `0`은 모든 카테고리 및 하위 카테고리를 표시합니다.; `-1`은 `0`과 비슷하지만 flat하게 표시합니다.; `1`은 최상위 계층의 카테고리들만 표시합니다. | 0 -`class` | 카테고리 목록의 Class명. | category -`transform` | 카테고리 이름의 표시 방식을 변경하는 기능. | -`suffix` | 링크에 접미사를 붙입니다. | None +| 옵션 | 설명 | 기본 값 | +| ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | +| `orderby` | 카테고리 정렬 기준 | name | +| `order` | 정렬 방식. `1`, `asc`은 오름차순; `-1`, `desc`은 내림차순 | 1 | +| `show_count` | 각 카테고리 별 포스트의 번호를 표시합니다. | true | +| `style` | 카테고리 목록 표시의 스타일. `list`는 카테고리 목록을 순서없이 표시합니다. | list | +| `separator` | 카테고리 별 구분자. (`style`이 `list`가 아닐 때만 동작합니다.) | , | +| `depth` | 카테고리의 계층을 표시합니다. `0`은 모든 카테고리 및 하위 카테고리를 표시합니다.; `-1`은 `0`과 비슷하지만 flat하게 표시합니다.; `1`은 최상위 계층의 카테고리들만 표시합니다. | 0 | +| `class` | 카테고리 목록의 Class명. | category | +| `transform` | 카테고리 이름의 표시 방식을 변경하는 기능. | +| `suffix` | 링크에 접미사를 붙입니다. | None | ### list_tags 모든 태그의 목록을 삽입합니다. -``` js +```js <%- list_tags([options]) %> ``` -옵션 | 설명 | 기본 값 ---- | --- | --- -`orderby` | 태그 정렬 기준 | name -`order` | 정렬 방식. `1`, `asc`은 오름차순; `-1`, `desc`은 내림차순 | 1 -`show_count` | 각 태그 별 포스트의 번호를 표시합니다. | true -`style` | 태그 목록 표시의 스타일. `list`는 태그 목록을 순서없이 표시합니다. | list -`separator` | 태그 별 구분자. (`style`이 `list`가 아닐 때만 동작합니다.) | , -`class` | Class name of tag list (string) or customize each tag's class (object, see below). | tag -`transform` | 태그 이름의 표시 방식을 변경하는 기능. | -`amount` | 표시되는 태그의 개수. (0 = 무한대) | 0 -`suffix` | 링크에 접미사를 붙입니다. | None +| 옵션 | 설명 | 기본 값 | +| ------------ | ---------------------------------------------------------------------------------- | ------- | +| `orderby` | 태그 정렬 기준 | name | +| `order` | 정렬 방식. `1`, `asc`은 오름차순; `-1`, `desc`은 내림차순 | 1 | +| `show_count` | 각 태그 별 포스트의 번호를 표시합니다. | true | +| `style` | 태그 목록 표시의 스타일. `list`는 태그 목록을 순서없이 표시합니다. | list | +| `separator` | 태그 별 구분자. (`style`이 `list`가 아닐 때만 동작합니다.) | , | +| `class` | Class name of tag list (string) or customize each tag's class (object, see below). | tag | +| `transform` | 태그 이름의 표시 방식을 변경하는 기능. | +| `amount` | 표시되는 태그의 개수. (0 = 무한대) | 0 | +| `suffix` | 링크에 접미사를 붙입니다. | None | Class advanced customization: -Option | Description | Default ---- | --- | --- -`class.ul` | `<ul>` class name (only for style `list`) | `tag-list` (list style) -`class.li` | `<li>` class name (only for style `list`) | `tag-list-item` (list style) -`class.a` | `<a>` class name | `tag-list-link` (list style) `tag-link` (normal style) -`class.label` | `<span>` class name where the tag label is stored (only for normal style, when `class.label` is set the label is put in a `<span>`) | `tag-label` (normal style) -`class.count` | `<span>` class name where the tag counter is stored (only when `show_count` is `true`) | `tag-list-count` (list style) `tag-count` (normal style) +| Option | Description | Default | +| ------------- | ----------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------- | +| `class.ul` | `<ul>` class name (only for style `list`) | `tag-list` (list style) | +| `class.li` | `<li>` class name (only for style `list`) | `tag-list-item` (list style) | +| `class.a` | `<a>` class name | `tag-list-link` (list style) `tag-link` (normal style) | +| `class.label` | `<span>` class name where the tag label is stored (only for normal style, when `class.label` is set the label is put in a `<span>`) | `tag-label` (normal style) | +| `class.count` | `<span>` class name where the tag counter is stored (only when `show_count` is `true`) | `tag-list-count` (list style) `tag-count` (normal style) | Examples: @@ -566,60 +567,60 @@ Examples: 아카이브 목록을 삽입합니다. -``` js +```js <%- list_archives([options]) %> ``` -옵션 | 설명 | 기본 값 ---- | --- | --- -`type` | 형식. 이 값은 `yearly` 또는 `monthly`입니다. | monthly -`order` | 정렬 방식. `1`, `asc`은 오름차순; `-1`, `desc`은 내림차순 | 1 -`show_count` | 각 아카이브에 대한 포스트의 개수를 표시합니다. | true -`format` | 날짜 형태 | MMMM YYYY -`style` | 아카이브 목록 표시의 스타일. `list`는 아카이브 목록을 순서없이 표시합니다. | list -`separator` | 아카이브 간 구분자. (`style`이 `list`가 아닐 때만 동작합니다.) | , -`class` | 아카이브 목록의 Class명. | archive -`transform` | 아카이브 이름의 표시 방식을 변경하는 기능. | +| 옵션 | 설명 | 기본 값 | +| ------------ | -------------------------------------------------------------------------- | --------- | +| `type` | 형식. 이 값은 `yearly` 또는 `monthly`입니다. | monthly | +| `order` | 정렬 방식. `1`, `asc`은 오름차순; `-1`, `desc`은 내림차순 | 1 | +| `show_count` | 각 아카이브에 대한 포스트의 개수를 표시합니다. | true | +| `format` | 날짜 형태 | MMMM YYYY | +| `style` | 아카이브 목록 표시의 스타일. `list`는 아카이브 목록을 순서없이 표시합니다. | list | +| `separator` | 아카이브 간 구분자. (`style`이 `list`가 아닐 때만 동작합니다.) | , | +| `class` | 아카이브 목록의 Class명. | archive | +| `transform` | 아카이브 이름의 표시 방식을 변경하는 기능. | ### list_posts 포스트의 목록을 삽입합니다. -``` js +```js <%- list_posts([options]) %> ``` -옵션 | 설명 | 기본 값 ---- | --- | --- -`orderby` | 포스트 정렬 기준 | date -`order` | 정렬 방식. `1`, `asc`은 오름차순; `-1`, `desc`은 내림차순 | 1 -`style` | 포스트 목록 표시의 스타일. `list`는 포스트 목록을 순서없이 표시합니다. | list -`separator` | 포스트 간 구분자. (`style`이 `list`각 아닐 때만 동작하빈다.) | , -`class` | 포스트 목록의 Class명. | post -`amount` | 표시되는 포스트의 개수. (0 = 무한대) | 6 -`transform` | 포스트 이름의 표시 방식을 변경하는 기능. | +| 옵션 | 설명 | 기본 값 | +| ----------- | ---------------------------------------------------------------------- | ------- | +| `orderby` | 포스트 정렬 기준 | date | +| `order` | 정렬 방식. `1`, `asc`은 오름차순; `-1`, `desc`은 내림차순 | 1 | +| `style` | 포스트 목록 표시의 스타일. `list`는 포스트 목록을 순서없이 표시합니다. | list | +| `separator` | 포스트 간 구분자. (`style`이 `list`각 아닐 때만 동작하빈다.) | , | +| `class` | 포스트 목록의 Class명. | post | +| `amount` | 표시되는 포스트의 개수. (0 = 무한대) | 6 | +| `transform` | 포스트 이름의 표시 방식을 변경하는 기능. | ### tagcloud 태그 클라우드를 삽입합니다. -``` js +```js <%- tagcloud([tags], [options]) %> ``` -옵션 | 설명 | 기본 값 ---- | --- | --- -`min_font` | 최소 폰트 크기 | 10 -`max_font` | 최대 폰트 크기 | 20 -`unit` | 폰트 크기의 단위 | px -`amount` | 태그의 총 개수 | 40 -`orderby` | 태그의 정렬 기준 | name -`order` | 정렬 방식. `1`, `asc`은 오름차순; `-1`, `desc`은 내림차순 | 1 -`color` | 태그 클라우드에 색상을 입힙니다. | false -`start_color` | 시작 색상. 16진수 색상 (`#b700ff`), rgba (`rgba(183, 0, 255, 1)`), hsla (`hsla(283, 100%, 50%, 1)`), [color keywords]을 사용할 수 있습니다. 이 옵션은 `color`가 true일 때만 동작합니다. | -`end_color` | 종료 색상. 16진수 색상 (`#b700ff`), rgba (`rgba(183, 0, 255, 1)`), hsla (`hsla(283, 100%, 50%, 1)`), [color keywords]. 이 옵션은 `color`가 true일 때만 동작합니다. | -`class` | Class name prefix of tags -`level` | The number of different class names. This option only works when `class` is set. | 10 +| 옵션 | 설명 | 기본 값 | +| ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| `min_font` | 최소 폰트 크기 | 10 | +| `max_font` | 최대 폰트 크기 | 20 | +| `unit` | 폰트 크기의 단위 | px | +| `amount` | 태그의 총 개수 | 40 | +| `orderby` | 태그의 정렬 기준 | name | +| `order` | 정렬 방식. `1`, `asc`은 오름차순; `-1`, `desc`은 내림차순 | 1 | +| `color` | 태그 클라우드에 색상을 입힙니다. | false | +| `start_color` | 시작 색상. 16진수 색상 (`#b700ff`), rgba (`rgba(183, 0, 255, 1)`), hsla (`hsla(283, 100%, 50%, 1)`), [color keywords]을 사용할 수 있습니다. 이 옵션은 `color`가 true일 때만 동작합니다. | +| `end_color` | 종료 색상. 16진수 색상 (`#b700ff`), rgba (`rgba(183, 0, 255, 1)`), hsla (`hsla(283, 100%, 50%, 1)`), [color keywords]. 이 옵션은 `color`가 true일 때만 동작합니다. | +| `class` | Class name prefix of tags | +| `level` | The number of different class names. This option only works when `class` is set. | 10 | ## Miscellaneous @@ -627,35 +628,35 @@ Examples: Paginator를 삽입합니다. -``` js +```js <%- paginator(options) %> ``` -옵션 | 설명 | 기본 값 ---- | --- | --- -`base` | 기준 URL | / -`format` | URL 형식 | page/%d/ -`total` | 페이지의 총 개수 | 1 -`current` | 현재 페이지의 번호 | 0 -`prev_text` | 이전 페이지의 링크 텍스트. `prev_next`가 true일 때만 동작합니다. | Prev -`next_text` | 다음 페이지의 링크 텍스트. `prev_next`가 true일 때만 동작합니다. | Next -`space` | 빈 공간을 나타내는 텍스트 | &hellp; -`prev_next` | 이전, 다음 링크를 표시합니다. | true -`end_size` | 시작/종료 측에 페이지의 개수를 표시합니다. | 1 -`mid_size` | 현재 페이지의 양쪽에 페이지의 개수를 표시합니다. 현재 페이지는 포함하지 않은 개수입니다. | 2 -`show_all` | 모든 페이지를 표시합니다. true로 설정되어있다면, `end_size`와 `mid_size`는 동작하지 않습니다. | false -`escape` | Escape HTML tags | true +| 옵션 | 설명 | 기본 값 | +| ----------- | --------------------------------------------------------------------------------------------- | -------- | +| `base` | 기준 URL | / | +| `format` | URL 형식 | page/%d/ | +| `total` | 페이지의 총 개수 | 1 | +| `current` | 현재 페이지의 번호 | 0 | +| `prev_text` | 이전 페이지의 링크 텍스트. `prev_next`가 true일 때만 동작합니다. | Prev | +| `next_text` | 다음 페이지의 링크 텍스트. `prev_next`가 true일 때만 동작합니다. | Next | +| `space` | 빈 공간을 나타내는 텍스트 | &hellp; | +| `prev_next` | 이전, 다음 링크를 표시합니다. | true | +| `end_size` | 시작/종료 측에 페이지의 개수를 표시합니다. | 1 | +| `mid_size` | 현재 페이지의 양쪽에 페이지의 개수를 표시합니다. 현재 페이지는 포함하지 않은 개수입니다. | 2 | +| `show_all` | 모든 페이지를 표시합니다. true로 설정되어있다면, `end_size`와 `mid_size`는 동작하지 않습니다. | false | +| `escape` | Escape HTML tags | true | **Examples:** -``` js +```js <%- paginator({ prev_text: '<', next_text: '>' }) %> ``` -``` html +```html <!-- Rendered as --> <a href="/1/"><</a> <a href="/1/">1</a> @@ -664,7 +665,7 @@ Paginator를 삽입합니다. <a href="/3/">></a> ``` -``` js +```js <%- paginator({ prev_text: '<i class="fa fa-angle-left"></i>', next_text: '<i class="fa fa-angle-right"></i>', @@ -672,7 +673,7 @@ Paginator를 삽입합니다. }) %> ``` -``` html +```html <!-- Rendered as --> <a href="/1/"><i class="fa fa-angle-left"></i></a> <a href="/1/">1</a> @@ -685,33 +686,33 @@ Paginator를 삽입합니다. Google 검색 form을 삽입합니다. -``` js +```js <%- search_form(options) %> ``` -옵션 | 설명 | 기본 값 ---- | --- | --- -`class` | Form의 Class명 | search-form -`text` | 검색의 hint에 들어갈 문장 | Search -`button` | 검색 버튼을 표시합니다. boolean 또는 string 값을 가질 수 있습니다. 이 값이 string이면 해당 문자열은 버튼에 표시됩니다. | false +| 옵션 | 설명 | 기본 값 | +| -------- | ---------------------------------------------------------------------------------------------------------------------- | ----------- | +| `class` | Form의 Class명 | search-form | +| `text` | 검색의 hint에 들어갈 문장 | Search | +| `button` | 검색 버튼을 표시합니다. boolean 또는 string 값을 가질 수 있습니다. 이 값이 string이면 해당 문자열은 버튼에 표시됩니다. | false | ### number_format 숫자의 형식을 지정합니다. -``` js +```js <%- number_format(number, [options]) %> ``` -옵션 | 설명 | 기본 값 ---- | --- | --- -`precision` | 수의 정밀도. `false` 또는 음수가 아닌 정수 값을 가집니다. | false -`delimiter` | 1000 단위의 구분자. | , -`separator` | 분수와 정수의 구분자. | . +| 옵션 | 설명 | 기본 값 | +| ----------- | --------------------------------------------------------- | ------- | +| `precision` | 수의 정밀도. `false` 또는 음수가 아닌 정수 값을 가집니다. | false | +| `delimiter` | 1000 단위의 구분자. | , | +| `separator` | 분수와 정수의 구분자. | . | **예시:** -``` js +```js <%- number_format(12345.67, {precision: 1}) %> // 12,345.68 @@ -732,13 +733,13 @@ Google 검색 form을 삽입합니다. Inserts [generator tag](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta). -``` js +```js <%- meta_generator() %> ``` **Examples:** -``` js +```js <%- meta_generator() %> // <meta name="generator" content="Hexo 4.0.0"> ``` @@ -747,47 +748,47 @@ Inserts [generator tag](https://developer.mozilla.org/en-US/docs/Web/HTML/Elemen [Open Graph] 데이터를 삽입합니다. -``` js +```js <%- open_graph([options]) %> ``` -옵션 | 설명 | 기본 값 ---- | --- | --- -`title` | 페이지 제목 (`og:title`) | `page.title` -`type` | 페이지 형태 (`og:type`) | article(post page)<br>website(non-post page) -`url` | 페이지 URL (`og:url`) | `url` -`image` | 페이지 커버 (`og:image`) | All images in the content -`author` | Article author (`og:article:author`) | `config.author` -`date` | Article published time (`og:article:published_time`) | Page published time -`updated` | Article modified time (`og:article:modified_time`) | Page modified time -`language` | Article language (`og:locale`) | `page.lang \|\| page.language \|\| config.language` -`site_name` | 사이트 이름 (`og:site_name`) | `config.title` -`description` | 페이지 설명 (`og:description`) | Page excerpt or first 200 characters of the content -`twitter_card` | Twitter card type (`twitter:card`) | summary -`twitter_id` | Twitter ID (`twitter:creator`) | -`twitter_site` | Twitter Site (`twitter:site`) | -`google_plus` | Google+ profile link | -`fb_admins` | Facebook admin ID | -`fb_app_id` | Facebook App ID | +| 옵션 | 설명 | 기본 값 | +| -------------- | ---------------------------------------------------- | --------------------------------------------------- | +| `title` | 페이지 제목 (`og:title`) | `page.title` | +| `type` | 페이지 형태 (`og:type`) | article(post page)<br>website(non-post page) | +| `url` | 페이지 URL (`og:url`) | `url` | +| `image` | 페이지 커버 (`og:image`) | All images in the content | +| `author` | Article author (`og:article:author`) | `config.author` | +| `date` | Article published time (`og:article:published_time`) | Page published time | +| `updated` | Article modified time (`og:article:modified_time`) | Page modified time | +| `language` | Article language (`og:locale`) | `page.lang \|\| page.language \|\| config.language` | +| `site_name` | 사이트 이름 (`og:site_name`) | `config.title` | +| `description` | 페이지 설명 (`og:description`) | Page excerpt or first 200 characters of the content | +| `twitter_card` | Twitter card type (`twitter:card`) | summary | +| `twitter_id` | Twitter ID (`twitter:creator`) | +| `twitter_site` | Twitter Site (`twitter:site`) | +| `google_plus` | Google+ profile link | +| `fb_admins` | Facebook admin ID | +| `fb_app_id` | Facebook App ID | ### toc 헤딩 태그(h1~h6)를 파싱하여 목차(Table of Content)를 삽입합니다. -``` js +```js <%- toc(str, [options]) %> ``` -옵션 | 설명 | 기본 값 ---- | --- | --- -`class` | Class명 | toc -`list_number` | 목록 번호를 표시합니다. | true -`max_depth` | Maximum heading depth of generated toc | 6 -`min_depth` | Minimum heading depth of generated toc | 1 +| 옵션 | 설명 | 기본 값 | +| ------------- | -------------------------------------- | ------- | +| `class` | Class명 | toc | +| `list_number` | 목록 번호를 표시합니다. | true | +| `max_depth` | Maximum heading depth of generated toc | 6 | +| `min_depth` | Minimum heading depth of generated toc | 1 | **예시:** -``` js +```js <%- toc(page.content) %> ``` @@ -803,7 +804,7 @@ Please see below PRs. - https://github.com/hexojs/hexo/pull/4871 - https://github.com/hexojs/hexo-util/pull/269 - https://github.com/hexojs/hexo-renderer-markdown-it/pull/174 -{% endnote %} + {% endnote %} [color keywords]: http://www.w3.org/TR/css3-color/#svg-color [Moment.js]: http://momentjs.com/ diff --git a/source/ko/docs/index.md b/source/ko/docs/index.md index 3dbc74ae44..9a4b2a915b 100644 --- a/source/ko/docs/index.md +++ b/source/ko/docs/index.md @@ -1,6 +1,7 @@ --- title: Documentation --- + Hexo 문서에 오신 것을 환영합니다. Hexo 사용 중 문제가 발생한다면 [troubleshooting guide](troubleshooting.html)를 살펴보세요. 이슈가 발생했다면 [GitHub](https://github.com/hexojs/hexo/issues) 또는 [Google Group](https://groups.google.com/group/hexo) 에 내용을 등록해 주세요. ## Hexo는 무엇인가요? @@ -20,7 +21,7 @@ Hexo의 설치는 꽤 쉽습니다. 하지만, 설치 전에 몇 가지 요구 컴퓨터에 이미 이런 것들이 설치되어 있다면, 축하드립니다! 이제 npm을 이용하여 Hexo를 설치하기만 하면 됩니다. -``` bash +```bash $ npm install -g hexo-cli ``` @@ -66,7 +67,7 @@ If you installed Node.js using Snap, you may need to manually run `npm install` 위의 요구사항을 모두 설치하셨다면, npm을 통해 Hexo를 설치하세요. -``` bash +```bash $ npm install -g hexo-cli ``` @@ -78,15 +79,15 @@ Please note we do not provide bugfixes to past versions of Hexo. We highly recommend to always install the [latest version](https://www.npmjs.com/package/hexo?activeTab=versions) of Hexo and the [recommended version](#Requirements) of Node.js, whenever possible. -Hexo version | Minimum (Node.js version) | Less than (Node.js version) ---- | --- | --- -7.0+ | 14.0.0 | latest -6.2+ | 12.13.0 | latest -6.0+ | 12.13.0 | 18.5.0 -5.0+ | 10.13.0 | 12.0.0 -4.1 - 4.2 | 8.10 | 10.0.0 -4.0 | 8.6 | 8.10.0 -3.3 - 3.9 | 6.9 | 8.0.0 -3.2 - 3.3 | 0.12 | unknown -3.0 - 3.1 | 0.10 or iojs | unknown -0.0.1 - 2.8 | 0.10 | unknown \ No newline at end of file +| Hexo version | Minimum (Node.js version) | Less than (Node.js version) | +| ------------ | ------------------------- | --------------------------- | +| 7.0+ | 14.0.0 | latest | +| 6.2+ | 12.13.0 | latest | +| 6.0+ | 12.13.0 | 18.5.0 | +| 5.0+ | 10.13.0 | 12.0.0 | +| 4.1 - 4.2 | 8.10 | 10.0.0 | +| 4.0 | 8.6 | 8.10.0 | +| 3.3 - 3.9 | 6.9 | 8.0.0 | +| 3.2 - 3.3 | 0.12 | unknown | +| 3.0 - 3.1 | 0.10 or iojs | unknown | +| 0.0.1 - 2.8 | 0.10 | unknown | diff --git a/source/ko/docs/internationalization.md b/source/ko/docs/internationalization.md index 6f01f0540a..023e1c5927 100644 --- a/source/ko/docs/internationalization.md +++ b/source/ko/docs/internationalization.md @@ -1,9 +1,10 @@ --- title: Internationalization (i18n) --- + 당신의 웹 사이트를 서로 다른 언어로 표시하기 위해 internationalization을 사용할 수 있습니다. 기본 언어의 변경은 `_config.yml` 파일의 `language`를 수정하면 됩니다. 다중 언어를 설정할 수도 있고 기본 언어의 순서를 수정할 수도 있습니다. -``` yaml +```yaml language: zh-tw language: @@ -19,7 +20,7 @@ language: `__` 또는 `_p`를 사용하면 템플릿에서의 문자열의 번역을 위한 helper를 사용할 수 있습니다. `__`는 일반적인 사용 방법이고 `_p`는 여러 개의 문자열을 위해 사용하는 방법입니다. 아래 예시를 보세요. -``` yaml en.yml +```yaml en.yml index: title: Home add: Add @@ -29,7 +30,7 @@ index: other: %d videos ``` -``` js +```js <%= __('index.title') %> // Home @@ -41,13 +42,13 @@ index: 페이지에서 사용할 언어는 front-matter에서도 설정이 가능합니다. `_config.yml` 파일의 `i18n_dir` 항목을 수정하면 Hexo가 자동으로 감지할 수 있습니다. -``` yaml +```yaml i18n_dir: :lang ``` `i18n_dir` 설정의 기본 값은 `:lang` 이며, Hexo는 URL의 첫 번째 세그먼트에서 언어를 감지합니다. -``` plain +```plain /index.html => en /archives/index.html => en /zh-tw/index.html => zh-tw diff --git a/source/ko/docs/migration.md b/source/ko/docs/migration.md index 300ade228b..d6bc82475e 100644 --- a/source/ko/docs/migration.md +++ b/source/ko/docs/migration.md @@ -1,17 +1,18 @@ --- title: Migration --- + ## RSS 먼저 `hexo-migrator-rss` 플러그인을 설치하세요. -``` bash +```bash $ npm install hexo-migrator-rss --save ``` 플러그인 설치 후에는 아래의 명령어를 수행하여 RSS의 모든 포스트를 마이그레이션 하세요. `source`에는 파일 경로나 URL를 사용할 수 있습니다. -``` bash +```bash $ hexo migrate rss <source> ``` @@ -21,7 +22,7 @@ Jekyll의 `_posts` 폴더의 모든 파일을 Hexo의 `source/_posts` 폴더로 `_config.yml`파일의 `new_post_name` 설정을 다음과 같이 수정하세요. -``` yaml +```yaml new_post_name: :year-:month-:day-:title.md ``` @@ -31,7 +32,7 @@ Octopress `source/_posts` 폴더의 모든 파일을 Hexo의 `source/_posts` 폴 `_config.yml`파일의 `new_post_name` 설정을 다음과 같이 수정하세요. -``` yaml +```yaml new_post_name: :year-:month-:day-:title.md ``` @@ -39,7 +40,7 @@ new_post_name: :year-:month-:day-:title.md 먼저, `hexo-migrator-wordpress` plugin을 설치하세요. -``` bash +```bash $ npm install hexo-migrator-wordpress --save ``` @@ -47,7 +48,7 @@ WordPress의 dashboard에서 "Tools" → "Export" → "WordPress" 를 통해 사 그 후 아래 명령어를 수행하세요: -``` bash +```bash $ hexo migrate wordpress <source> ``` diff --git a/source/ko/docs/one-command-deployment.md b/source/ko/docs/one-command-deployment.md index 7181c135f7..5152ab768a 100644 --- a/source/ko/docs/one-command-deployment.md +++ b/source/ko/docs/one-command-deployment.md @@ -1,27 +1,28 @@ --- title: Deployment --- + Hexo는 빠르고 쉬운 deployment전략을 제공합니다. 웹 사이트를 서버에 deploy하기 위해 하나의 명령어만 수행하면 됩니다. -``` bash +```bash $ hexo deploy ``` 처음 개발을 진행하기 전에, `_config.yml` 파일의 설정을 수정할 필요가 있습니다. Deployment를 원하는 곳을 아래 예시처럼 `type` 필드에 넣습니다. -``` yaml +```yaml deploy: type: git ``` 여러 곳에 동시에 deploy할 수도 있습니다. Hexo는 순차적으로 deploy를 수행합니다. -``` yaml +```yaml deploy: -- type: git - repo: -- type: heroku - repo: + - type: git + repo: + - type: heroku + repo: ``` Refer to the [Plugins](https://hexo.io/plugins/) list for more deployment plugins. @@ -44,17 +45,17 @@ deploy: message: [message] ``` -Option | Description | Default ---- | --- | --- -`repo` | URL of the target repository | -`branch` | Branch name. | `gh-pages` (GitHub)<br>`coding-pages` (Coding.net)<br>`master` (others) -`message` | Customize commit message. | `Site updated: {% raw %}{{ now('YYYY-MM-DD HH:mm:ss') }}{% endraw %}` -`token` | Optional token value to authenticate with the repo. Prefix with `$` to read token from environment variable +| Option | Description | Default | +| --------- | ----------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- | +| `repo` | URL of the target repository | +| `branch` | Branch name. | `gh-pages` (GitHub)<br>`coding-pages` (Coding.net)<br>`master` (others) | +| `message` | Customize commit message. | `Site updated: {% raw %}{{ now('YYYY-MM-DD HH:mm:ss') }}{% endraw %}` | +| `token` | Optional token value to authenticate with the repo. Prefix with `$` to read token from environment variable | 3. Deploy your site `hexo clean && hexo deploy`. - - You will be prompted with username and password of the target repository, unless you authenticate with a token or ssh key. - - hexo-deployer-git does not store your username and password. Use [git-credential-cache](https://git-scm.com/docs/git-credential-cache) to store them temporarily. +- You will be prompted with username and password of the target repository, unless you authenticate with a token or ssh key. +- hexo-deployer-git does not store your username and password. Use [git-credential-cache](https://git-scm.com/docs/git-credential-cache) to store them temporarily. 4. Navigate to your repository settings and change the "Pages" branch to `gh-pages` (or the branch specified in your config). The deployed site should be live on the link shown on the "Pages" setting. @@ -62,35 +63,35 @@ Option | Description | Default [hexo-deployer-heroku]을 설치합니다. -``` bash +```bash $ npm install hexo-deployer-heroku --save ``` 설정을 수정합니다. -``` yaml +```yaml deploy: type: heroku repo: <repository url> message: [message] ``` -옵션 | 설명 ---- | --- -`repo`, `repository` | Heroku 저장소 URL -`message` | Commit message를 수정합니다. (기본값 - `Site updated: {% raw %}{{ now('YYYY-MM-DD HH:mm:ss') }}{% endraw %}`) +| 옵션 | 설명 | +| -------------------- | ------------------------------------------------------------------------------------------------------------- | +| `repo`, `repository` | Heroku 저장소 URL | +| `message` | Commit message를 수정합니다. (기본값 - `Site updated: {% raw %}{{ now('YYYY-MM-DD HH:mm:ss') }}{% endraw %}`) | ## Rsync [hexo-deployer-rsync]를 설치합니다. -``` bash +```bash $ npm install hexo-deployer-rsync --save ``` 설정을 수정합니다. -``` yaml +```yaml deploy: type: rsync host: <host> @@ -102,49 +103,49 @@ deploy: ignore_errors: [true|false] ``` -옵션 | 설명 | 기본값 ---- | --- | --- -`host` | 원격 호스트의 주소 | -`user` | 사용자명 | -`root` | 원격 호스트의 루트 디렉토리 | -`port` | 포트 | 22 -`delete` | 원격 호스트의 오래된 파일을 삭제합니다. | true -`verbose` | Verbose 메시지를 표시합니다. | true -`ignore_errors` | 에러를 무시합니다. | false +| 옵션 | 설명 | 기본값 | +| --------------- | --------------------------------------- | ------ | +| `host` | 원격 호스트의 주소 | +| `user` | 사용자명 | +| `root` | 원격 호스트의 루트 디렉토리 | +| `port` | 포트 | 22 | +| `delete` | 원격 호스트의 오래된 파일을 삭제합니다. | true | +| `verbose` | Verbose 메시지를 표시합니다. | true | +| `ignore_errors` | 에러를 무시합니다. | false | ## OpenShift [hexo-deployer-openshift]를 설치합니다. -``` bash +```bash $ npm install hexo-deployer-openshift --save ``` 설정을 수정합니다. -``` yaml +```yaml deploy: type: openshift repo: <repository url> message: [message] ``` -옵션 | 설명 ---- | --- -`repo` | OpenShift 저장소 URL -`message` | Commit message를 수정합니다. (기본값 - `Site updated: {% raw %}{{ now('YYYY-MM-DD HH:mm:ss') }}{% endraw %}`) +| 옵션 | 설명 | +| --------- | ------------------------------------------------------------------------------------------------------------- | +| `repo` | OpenShift 저장소 URL | +| `message` | Commit message를 수정합니다. (기본값 - `Site updated: {% raw %}{{ now('YYYY-MM-DD HH:mm:ss') }}{% endraw %}`) | ## FTPSync [hexo-deployer-ftpsync]를 설치합니다. -``` bash +```bash $ npm install hexo-deployer-ftpsync --save ``` 설정을 수정합니다. -``` yaml +```yaml deploy: type: ftpsync host: <host> @@ -156,15 +157,17 @@ deploy: verbose: [true|false] ``` -옵션 | 설명 | 기본값 ---- | --- | --- -`host` | 원격 호스트의 주소 | -`user` | 사용자명 | -`pass` | 비밀번호 | -`remote` | 원격 호스트의 루트 디렉토리 | `/` -`port` | 포트 | 21 -`clear` | Remove all files and directories from the remote directory before upload | false -`verbose` | Verbose 메시지를 표시합니다. | false +| 옵션 | 설명 | 기본값 | +| ------------- | ------------------------------------------------------------------------ | ------ | +| `host` | 원격 호스트의 주소 | +| `user` | 사용자명 | +| `pass` | 비밀번호 | +| `remote` | 원격 호스트의 루트 디렉토리 | `/` | +| `port` | 포트 | 21 | +| `clear` | Remove all files and directories from the remote directory before upload | false | +| `ignore` | 호스트 파일들과 원격 파일들을 무시합니다. | +| `connections` | 연결 번호 | 1 | +| `verbose` | Verbose 메시지를 표시합니다. | false | ## Vercel @@ -222,8 +225,8 @@ After a few moments, your website will be deployed. 2. 구성을 수정합니다. - ``` yaml - deploy: +```yaml +deploy: - type: rss3 endpoint: https://hub.rss3.io privateKey: 47e18d6c386898b424025cd9db446f779ef24ad33a26c499c87bb3d9372540ba @@ -233,15 +236,15 @@ After a few moments, your website will be deployed. api: key: d693df715d3631e489d6 secret: ee8b74626f12b61c1a4bde3b8c331ad390567c86ba779c9b18561ee92c1cbff0 - ``` - -|매개변수 |설명 | -| ------------------ | ---------------------- | -| `endpoint` | RSS3 Hub에 대한 링크 | -| `privateKey` | 개인 키, 64바이트 | -| `ipfs/deploy` | IPFS에 배포할지 여부 | -| `ipfs/gateway` | IPFS API 게이트웨이 | -| `ipfs/api/key` | IPFS 게이트웨이 관련 검증 내용 | +``` + +| 매개변수 | 설명 | +| ----------------- | ------------------------------ | +| `endpoint` | RSS3 Hub에 대한 링크 | +| `privateKey` | 개인 키, 64바이트 | +| `ipfs/deploy` | IPFS에 배포할지 여부 | +| `ipfs/gateway` | IPFS API 게이트웨이 | +| `ipfs/api/key` | IPFS 게이트웨이 관련 검증 내용 | | `ipfs/api/secret` | IPFS 게이트웨이 관련 검증 내용 | 3. 정적 파일 생성 diff --git a/source/ko/docs/permalinks.md b/source/ko/docs/permalinks.md index 3ccfdd307a..1055478a4a 100644 --- a/source/ko/docs/permalinks.md +++ b/source/ko/docs/permalinks.md @@ -1,84 +1,85 @@ --- title: Permalinks --- + `_config.yml` 파일 또는 각 포스트의 front-matter에 permalink의 형식을 지정할 수 있습니다. ### 변수 Besides the following variables, you can use any attributes in the permalink except `:path` and `:permalink`. -변수 | 설명 ---- | --- -`:year` | 포스트를 배포한 연도 (4-digit) -`:month` | 포스트를 배포한 월 (2-digit) -`:i_month` | 포스트를 배포한 월 (앞에 붙는 0은 생략) -`:day` | 포스트를 배포한 날 (2-digit) -`:i_day` | 포스트를 배포한 날 (앞에 붙는 0은 생략) -`:hour` | Published hour of posts (2-digit) -`:minute` | Published minute of posts (2-digit) -`:second` | Published second of posts (2-digit) -`:title` | 파일명 (relative to "source/_posts/" folder) -`:name` | 파일명 -`:post_title` | Post title -`:id` | 포스트 ID (_not persistent across [cache reset](/ko/docs/commands#clean)_) -`:category` | 포스트가 속한 카테고리. 지정하지 않으면 `default_category` 값을 사용합니다. -`:hash` | SHA1 hash of filename (same as `:title`) and date (12-hexadecimal) +| 변수 | 설명 | +| ------------- | --------------------------------------------------------------------------- | +| `:year` | 포스트를 배포한 연도 (4-digit) | +| `:month` | 포스트를 배포한 월 (2-digit) | +| `:i_month` | 포스트를 배포한 월 (앞에 붙는 0은 생략) | +| `:day` | 포스트를 배포한 날 (2-digit) | +| `:i_day` | 포스트를 배포한 날 (앞에 붙는 0은 생략) | +| `:hour` | Published hour of posts (2-digit) | +| `:minute` | Published minute of posts (2-digit) | +| `:second` | Published second of posts (2-digit) | +| `:title` | 파일명 (relative to "source/\_posts/" folder) | +| `:name` | 파일명 | +| `:post_title` | Post title | +| `:id` | 포스트 ID (_not persistent across [cache reset](/ko/docs/commands#clean)_) | +| `:category` | 포스트가 속한 카테고리. 지정하지 않으면 `default_category` 값을 사용합니다. | +| `:hash` | SHA1 hash of filename (same as `:title`) and date (12-hexadecimal) | Permalink 내의 각 변수의 기본 값을 `permalink_defaults` 설정을 통해 정의할 수 있습니다. -``` yaml +```yaml permalink_defaults: lang: en ``` ### 예시 -``` yaml source/_posts/hello-world.md +```yaml source/_posts/hello-world.md title: Hello World date: 2013-07-14 17:01:34 categories: -- foo -- bar + - foo + - bar ``` -설정 | 결과 ---- | --- -`:year/:month/:day/:title/` | 2013/07/14/hello-world/ -`:year-:month-:day-:title.html` | 2013-07-14-hello-world.html -`:category/:title/` | foo/bar/hello-world/ -`:title-:hash/` | hello-world-a2c8ac003b43/ +| 설정 | 결과 | +| ------------------------------- | --------------------------- | +| `:year/:month/:day/:title/` | 2013/07/14/hello-world/ | +| `:year-:month-:day-:title.html` | 2013-07-14-hello-world.html | +| `:category/:title/` | foo/bar/hello-world/ | +| `:title-:hash/` | hello-world-a2c8ac003b43/ | -``` yaml source/_posts/lorem/hello-world.md +```yaml source/_posts/lorem/hello-world.md title: Hello World date: 2013-07-14 17:01:34 categories: -- foo -- bar + - foo + - bar ``` -설정 | 결과 ---- | --- -`:year/:month/:day/:title/` | 2013/07/14/lorem/hello-world/ -`:year/:month/:day/:name/` | 2013/07/14/hello-world/ +| 설정 | 결과 | +| --------------------------- | ----------------------------- | +| `:year/:month/:day/:title/` | 2013/07/14/lorem/hello-world/ | +| `:year/:month/:day/:name/` | 2013/07/14/hello-world/ | ### 다국어 지원 다국어 지원 사이트를 생성하기 위해, `new_post_name`과 `permalink`를 다음과 같이 수정해야 합니다. -``` yaml +```yaml new_post_name: :lang/:title.md permalink: :lang/:title/ ``` 새 post를 생성할 때, 다음과 같이 저장해야 합니다. -``` bash +```bash $ hexo new "Hello World" --lang tw # => source/_posts/tw/Hello-World.md ``` 그리고 URL은 다음과 같아야 합니다. -``` plain +```plain http://localhost:4000/tw/hello-world/ ``` diff --git a/source/ko/docs/plugins.md b/source/ko/docs/plugins.md index 1319deac8c..aa31e52b09 100644 --- a/source/ko/docs/plugins.md +++ b/source/ko/docs/plugins.md @@ -1,6 +1,7 @@ --- title: Plugins --- + Hexo는 파워풀한 플러그인 시스템을 가지고 있습니다. 코어 모듈의 소스 코드를 수정하지 않고도 쉽게 확장 기능을 구현할 수 있습니다. 아래에서 두 가지 종류의 Hexo 플러그인을 소개해 드립니다. ### 스크립트 @@ -13,7 +14,7 @@ Hexo는 파워풀한 플러그인 시스템을 가지고 있습니다. 코어 새 폴더는 반드시 다음 두 개의 파일을 가지고 있어야 합니다. 하나는 실제 JavaScript 코드이며, 하나는 플러그인의 목적 및 의존성에 대해 기술한 `package.json` 파일입니다. -``` plain +```plain . ├── index.js └── package.json @@ -21,7 +22,7 @@ Hexo는 파워풀한 플러그인 시스템을 가지고 있습니다. 코어 `package.json` 파일에는 최소한 `name`, `version`, `main` 세 가지 항목은 있어야 합니다. -``` json package.json +```json package.json { "name": "hexo-my-plugin", "version": "0.0.1", @@ -47,23 +48,21 @@ Hexo는 파워풀한 플러그인 시스템을 가지고 있습니다. 코어 1. Fork [hexojs/site] 2. 저장소를 당신의 컴퓨터에 clone하고 종속성이 있는 것들을 모두 설치합니다. - {% code %} - $ git clone https://github.com/<username>/site.git - $ cd site - $ npm install - {% endcode %} + {% code %} + $ git clone https://github.com/<username>/site.git + $ cd site + $ npm install + {% endcode %} 3. `source/_data/plugins.yml` 파일을 수정하여 당신의 플러그인을 추가합니다. - {% code %} - - name: hexo-server - description: Server module for Hexo. - link: https://github.com/hexojs/hexo-server - tags: - - official - - server - - console - {% endcode %} + {% code %} + + - name: hexo-server + description: Server module for Hexo. + link: https://github.com/hexojs/hexo-server + tags: - official - server - console + {% endcode %} 4. Branch에 push합니다. 5. Pull request를 생성하여 변경사항에 대해 기술합니다. diff --git a/source/ko/docs/server.md b/source/ko/docs/server.md index eaf4bb4a4a..2e5ee92034 100644 --- a/source/ko/docs/server.md +++ b/source/ko/docs/server.md @@ -1,23 +1,24 @@ --- title: Server --- + ## [hexo-server] Hexo 3의 릴리즈와 함께, server를 메인 모듈과 분리시켰습니다. server를 사용하여 시작하기 위해서는 먼저 [hexo-server]를 설치해야 합니다. -``` bash +```bash $ npm install hexo-server --save ``` 설치가 완료되었다면 server를 시작하기 위해 아래 명령을 수행해야 합니다. 당신의 웹 사이트는 기본값에 의해 `http://localhost:4000`로 실행됩니다. server가 구동되는 동안 Hexo는 파일이 변경되는 것을 감지하여 자동으로 업데이트 합니다. 따라서 수동으로 server를 재시작할 필요가 없습니다. -``` bash +```bash $ hexo server ``` 포트를 변경하고 싶거나 `EADDRINUSE` 에러가 발생한다면 `-p` 옵션을 사용하여 다른 포트를 설정해 보세요. -``` bash +```bash $ hexo server -p 5000 ``` @@ -25,7 +26,7 @@ $ hexo server -p 5000 Static mode에서는 `public` 폴더의 파일들만 제공되며 파일 감시 기능은 비활성화됩니다. server를 시작하기 전에 `hexo generate`를 수행해야 합니다. 이 방법은 production에서 주로 사용됩니다. -``` bash +```bash $ hexo server -s ``` @@ -33,7 +34,7 @@ $ hexo server -s Hexo는 기본적으로 `0.0.0.0`을 기본값으로 수행됩니다. 아래와 같은 방법으로 IP 설정을 변경할 수 있습니다. -``` bash +```bash $ hexo server -i 192.168.1.1 ``` @@ -43,7 +44,7 @@ $ hexo server -i 192.168.1.1 ### 설치하기 -``` bash +```bash $ curl get.pow.cx | sh ``` @@ -51,7 +52,7 @@ $ curl get.pow.cx | sh `~/.pow`에 대해 심볼릭 링크를 설정합니다. -``` bash +```bash $ cd ~/.pow $ ln -s /path/to/myapp ``` diff --git a/source/ko/docs/setup.md b/source/ko/docs/setup.md index d0deedbe01..cc5702e668 100644 --- a/source/ko/docs/setup.md +++ b/source/ko/docs/setup.md @@ -1,9 +1,10 @@ --- title: Setup --- + Hexo를 설치했다면, 타겟 `<folder>`의 Hexo를 초기화하기 위해 아래의 명령을 수행하세요. -``` bash +```bash $ hexo init <folder> $ cd <folder> $ npm install @@ -11,7 +12,7 @@ $ npm install 초기화가 완료되면 다음과 같은 폴더 구조를 가지게 될 것입니다. -``` plain +```plain . ├── _config.yml ├── package.json @@ -22,7 +23,7 @@ $ npm install └── themes ``` -### _config.yml +### \_config.yml 이 파일은 [환경설정](configuration.html) 파일입니다. 대부분의 설정을 여기서 할 수 있습니다. @@ -30,7 +31,7 @@ $ npm install 어플리케이션 데이터 파일입니다. [EJS](https://ejs.co/), [Stylus](http://learnboost.github.io/stylus/), [Markdown](http://daringfireball.net/projects/markdown/) 렌더러들이 기본으로 설치됩니다. 원한다면, 나중에 당신이 제거할 수도 있습니다. -``` json package.json +```json package.json { "name": "hexo-site", "version": "0.0.0", diff --git a/source/ko/docs/syntax-highlight.md b/source/ko/docs/syntax-highlight.md index 6d78697b8f..cc1327965e 100644 --- a/source/ko/docs/syntax-highlight.md +++ b/source/ko/docs/syntax-highlight.md @@ -17,7 +17,7 @@ code snippet code snippet {% endcode %} -``` [language] [title] [url] [link text] [additional options] +```[language] [title] [url] [link text] [additional options] code snippet ``` ```` @@ -35,9 +35,9 @@ highlight: auto_detect: false line_number: true line_threshold: 0 - tab_replace: '' + tab_replace: "" exclude_languages: - - example + - example wrap: true hljs: false prismjs: @@ -45,7 +45,7 @@ prismjs: preprocess: true line_number: true line_threshold: 0 - tab_replace: '' + tab_replace: "" ``` The YAML above is Hexo's default configuration. @@ -85,7 +85,7 @@ highlight: auto_detect: false line_number: true line_threshold: 0 - tab_replace: ' ' + tab_replace: " " exclude_languages: - example wrap: true @@ -116,18 +116,18 @@ Hexo adds line number by wrapping output inside `<figure>` and `<table>`: ```html <figure class="highlight yaml"> -<table> -<tbody> -<tr> - <td class="gutter"> - <pre><span class="line">1</span><br></pre> - </td> - <td class="code"> - <pre><span class="line"><span class="attr">hello:</span><span class="string">hexo</span></span><br></pre> - </td> -</tr> -</tbody> -</table> + <table> + <tbody> + <tr> + <td class="gutter"> + <pre><span class="line">1</span><br></pre> + </td> + <td class="code"> + <pre><span class="line"><span class="attr">hello:</span><span class="string">hexo</span></span><br></pre> + </td> + </tr> + </tbody> + </table> </figure> ``` @@ -186,7 +186,7 @@ prismjs: preprocess: true line_number: true line_threshold: 0 - tab_replace: '' + tab_replace: "" ``` Prismjs is disabled by default. You should set `highlight.enable` to `false` before enabling prismjs. diff --git a/source/ko/docs/tag-plugins.md b/source/ko/docs/tag-plugins.md index 45c069fb98..f824c20da8 100644 --- a/source/ko/docs/tag-plugins.md +++ b/source/ko/docs/tag-plugins.md @@ -1,6 +1,7 @@ --- title: Tag Plugins --- + 태그 플러그인은 포스트의 태그와는 다릅니다. Octopress로부터 가져온 것으로 특별한 컨텐츠를 당신의 포스트에 빠르게 추가할 수 있도록 도와주는 유용한 방법입니다. Although you can write your posts in any formats, but the tag plugins will always be available and syntax remains the same. @@ -83,14 +84,14 @@ code snippet Specify additional options in `option:value` format, e.g. `line_number:false first_line:5`. -Extra Options | Description | Default ---- | --- | --- -`line_number` | Show line number | `true` -`line_threshold` | Only show line numbers as long as the numbers of lines of the code block exceed such threshold. | `0` | -`highlight` | Enable code highlighting | `true` -`first_line` | Specify the first line number | `1` -`mark` | Line highlight specific line(s), each value separated by a comma. Specify number range using a dash<br>Example: `mark:1,4-7,10` will mark line 1, 4 to 7 and 10. | -`wrap` | Wrap the code block in [`<table>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table) | `true` +| Extra Options | Description | Default | +| ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| `line_number` | Show line number | `true` | +| `line_threshold` | Only show line numbers as long as the numbers of lines of the code block exceed such threshold. | `0` | +| `highlight` | Enable code highlighting | `true` | +| `first_line` | Specify the first line number | `1` | +| `mark` | Line highlight specific line(s), each value separated by a comma. Specify number range using a dash<br>Example: `mark:1,4-7,10` will mark line 1, 4 to 7 and 10. | +| `wrap` | Wrap the code block in [`<table>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table) | `true` | ### 예시 @@ -140,7 +141,7 @@ _.compact([0, 1, false, 2, '', 3]); ``` {% codeblock _.compact http://underscorejs.org/#compact Underscore.js %} -_.compact([0, 1, false, 2, '', 3]); +\_.compact([0, 1, false, 2, '', 3]); => [1, 2, 3] {% endcodeblock %} @@ -149,9 +150,9 @@ _.compact([0, 1, false, 2, '', 3]); 이 방법은 code block을 사용하는 것과 같습니다만 block을 구분하기 위해 세 개의 역 따옴표를 사용하는 점이 다릅니다. {% raw %} -``` [language] [title] [url] [link text] +`` [language] [title] [url] [link text] code snippet -``` +`` {% endraw %} ## Pull Quote @@ -289,6 +290,7 @@ For instance: ``` {% post_link hexo-4-released 'How to use <b> tag in title' %} ``` + {% post_link hexo-4-released 'How to use <b> tag in title' %} **Do not escape title.** @@ -296,6 +298,7 @@ For instance: ``` {% post_link hexo-4-released '<b>bold</b> custom title' false %} ``` + {% post_link hexo-4-released '<b>bold</b> custom title' false %} ## Include Assets @@ -318,32 +321,32 @@ _hexo-renderer-marked 3.1.0+ can (optionally) resolves the post's path of an ima `{% asset_img foo.jpg %}` -``` html -<img src="/2020/01/02/hello/foo.jpg"> +```html +<img src="/2020/01/02/hello/foo.jpg" /> ``` **Custom class** `{% asset_img post-image foo.jpg %}` -``` html -<img src="/2020/01/02/hello/foo.jpg" class="post-image"> +```html +<img src="/2020/01/02/hello/foo.jpg" class="post-image" /> ``` **Display size** `{% asset_img foo.jpg 500 400 %}` -``` html -<img src="/2020/01/02/hello/foo.jpg" width="500" height="400"> +```html +<img src="/2020/01/02/hello/foo.jpg" width="500" height="400" /> ``` **Title & Alt** `{% asset_img logo.svg "lorem ipsum'dolor'" %}` -``` html -<img src="/2020/01/02/hello/foo.jpg" title="lorem ipsum" alt="dolor"> +```html +<img src="/2020/01/02/hello/foo.jpg" title="lorem ipsum" alt="dolor" /> ``` ## Raw diff --git a/source/ko/docs/templates.md b/source/ko/docs/templates.md index db06ca5ae3..3524ee4d0f 100644 --- a/source/ko/docs/templates.md +++ b/source/ko/docs/templates.md @@ -1,38 +1,43 @@ --- title: Templates --- + 템플릿은 당신의 웹 사이트를 외관을 어떻게 표현할지 정의합니다. 아래 표는 페이지에 따른 적절한 템플릿을 소개합니다. 테마는 최소한 `index` 템플릿은 가지고 있어야 합니다. -템플릿 | 페이지 | 대비책 ---- | --- | --- -`index` | Home page | -`post` | Posts | `index` -`page` | Pages | `index` -`archive` | Archives | `index` -`category` | Category archives | `archive` -`tag` | Tag archives | `archive` +| 템플릿 | 페이지 | 대비책 | +| ---------- | ----------------- | --------- | +| `index` | Home page | +| `post` | Posts | `index` | +| `page` | Pages | `index` | +| `archive` | Archives | `index` | +| `category` | Category archives | `archive` | +| `tag` | Tag archives | `archive` | ## 레이아웃 페이지들이 비슷한 구조를 공유하는 경우 - 예를 들어, header와 footer를 갖는 두 개의 템플릿이 있다고 할 때 - 당신은 `layout`을 사용하여 구조적인 유사성을 나타낼 수 있습니다. 모든 레이아웃 파일은 템플릿의 컨텐츠를 표시할 `body` 변수를 가지고 있어야 합니다. -``` html index.ejs +```html index.ejs index ``` -``` html layout.ejs -<!DOCTYPE html> +```html layout.ejs +<!doctype html> <html> - <body><%- body %></body> + <body> + <%- body %> + </body> </html> ``` yields: -``` html -<!DOCTYPE html> +```html +<!doctype html> <html> - <body>index</body> + <body> + index + </body> </html> ``` @@ -42,18 +47,18 @@ yields: Partial은 템플릿끼리 구성 요소를 공유할 때 유용합니다. 일반적인 예로 header, footer, sidebar가 있습니다. Partial을 각각의 파일에 포함시켜서 당신의 웹 사이트를 좀 더 간단하게 유지보수 할 수 있습니다. -``` html partial/header.ejs +```html partial/header.ejs <h1 id="logo"><%= config.title %></h1> ``` -``` html index.ejs +```html index.ejs <%- partial('partial/header') %> <div id="content">Home page</div> ``` yields: -``` html +```html <h1 id="logo">My Site</h1> <div id="content">Home page</div> ``` @@ -62,18 +67,18 @@ yields: 템플릿 내에 지역 변수를 정의할 수 있고 이를 다른 팀플릿 내에서 사용할 수 있습니다. -``` html partial/header.ejs +```html partial/header.ejs <h1 id="logo"><%= title></h1> ``` -``` html index.ejs +```html index.ejs <%- partial('partial/header', {title: 'Hello World'}) %> <div id="content">Home page</div> ``` yields: -``` html +```html <h1 id="logo">Hello World</h1> <div id="content">Home page</div> ``` @@ -86,7 +91,7 @@ yields: Fragment caching은 header, footer, sidebar, 다른 정적인 컨텐츠를 사용할 때 최고입니다. -``` js +```js <%- fragment_cache('header', function(){ return '<header></header>'; }); @@ -94,7 +99,7 @@ Fragment caching은 header, footer, sidebar, 다른 정적인 컨텐츠를 사 그렇다 하더라도 Partial을 사용하는 것이 더 쉬울 수 있습니다. -``` js +```js <%- partial('header', {}, {cache: true}); ``` diff --git a/source/ko/docs/themes.md b/source/ko/docs/themes.md index d173757002..30eca7b7ae 100644 --- a/source/ko/docs/themes.md +++ b/source/ko/docs/themes.md @@ -1,9 +1,10 @@ --- title: Themes --- + Hexo theme를 만드는 것은 쉽습니다. - 새로운 폴더를 생성하기만 하면 됩니다. 당신의 테마의 사용을 위해 `_config.yml` 파일의 theme` 설정을 수정하세요. 테마는 아래의 구조를 가져야 합니다. -``` plain +```plain . ├── _config.yml ├── languages @@ -12,7 +13,7 @@ Hexo theme를 만드는 것은 쉽습니다. - 새로운 폴더를 생성하기 └── source ``` -### _config.yml +### \_config.yml 테마의 환경설정 파일입니다. Unlike the site's primary configuration file, server를 재시작하지 않고도 이 파일을 수정할 수 있습니다. @@ -24,7 +25,7 @@ Hexo theme를 만드는 것은 쉽습니다. - 새로운 폴더를 생성하기 레이아웃 폴더입니다. 이 폴더는 당신의 웹 사이트를 어떻게 보여줄지 정의한 테마 템플릿 파일을 포함합니다. Hexo는 기본적으로 [Nunjucks] 템플릿 엔진을 준비해 두었습니다. 하지만 당신은 [EJS], [Haml], [Jade], [Pug] 등 엔진을 대체할 다른 플러그인을 쉽게 설치할 수 있습니다. Hexo는 템플릿의 파일 확장자를 기반으로 템플릿 엔진을 선택합니다. -``` plain +```plain layout.ejs - uses EJS layout.njk - uses Nunjucks ``` @@ -48,28 +49,28 @@ Hexo는 모든 렌더링 가능한 파일들을 처리한 후 `public` 폴더에 1. Fork [hexojs/site] 2. 저장소를 당신의 컴퓨터에 clone하고 의존 사항들을 설치합니다. - ```shell - $ git clone https://github.com/<username>/site.git - $ cd site - $ npm install - ``` + ```shell + $ git clone https://github.com/<username>/site.git + $ cd site + $ npm install + ``` 3. `source/_data/themes.yml`를 수정하고 테마를 추가하세요. - ```yaml - - name: landscape - description: A brand new default theme for Hexo. - link: https://github.com/hexojs/hexo-theme-landscape - preview: http://hexo.io/hexo-theme-landscape - tags: - - official - - responsive - - widget - - two_column - - one_column - ``` - -4. `source/themes/screenshots`에 스크린샷을 추가하세요. 스크린샷의 이름은 테마와 동일해야 하며 반드시 사이즈가 800*500 픽셀인 PNG 파일이어야 합니다. + ```yaml + - name: landscape + description: A brand new default theme for Hexo. + link: https://github.com/hexojs/hexo-theme-landscape + preview: http://hexo.io/hexo-theme-landscape + tags: + - official + - responsive + - widget + - two_column + - one_column + ``` + +4. `source/themes/screenshots`에 스크린샷을 추가하세요. 스크린샷의 이름은 테마와 동일해야 하며 반드시 사이즈가 800\*500 픽셀인 PNG 파일이어야 합니다. 5. Branch에 push하세요. 6. 변경사항에 대한 설명을 포함하여 Pull request를 생성합니다. diff --git a/source/ko/docs/troubleshooting.md b/source/ko/docs/troubleshooting.md index 9aafbb06c5..8835d06ec6 100644 --- a/source/ko/docs/troubleshooting.md +++ b/source/ko/docs/troubleshooting.md @@ -1,18 +1,19 @@ --- title: Troubleshooting --- + Hexo 사용 중에 문제가 발생할 경우, 이 문서에 있는 해결책을 확인해 보세요. 자주 발생하는 문제에 대해 정리해 두었습니다. 만약 이 문서에서 해결 방안을 찾지 못하였다면 [GitHub](https://github.com/hexojs/hexo/issues) 또는 [Google Group](https://groups.google.com/group/hexo)을 검색해 보세요. ## YAML Parsing Error -``` plain +```plain JS-YAML: incomplete explicit mapping pair; a key node is missed at line 18, column 29: last_updated: Last updated: %s ``` 문자열이 콜론(:)을 포함하고 있다면 따옴표(")로 감싸주세요. -``` plain +```plain JS-YAML: bad indentation of a mapping entry at line 18, column 31: last_updated:"Last updated: %s" ``` @@ -23,13 +24,13 @@ Soft tab의 사용을 명확히 하고 콜론(:) 뒤에는 공백을 추가해 ## EMFILE Error -``` plain +```plain Error: EMFILE, too many open files ``` Node.js가 non-blocking I/O를 가지고 있음에도 불구하고, 동기적 I/O의 최대 개수는 아직도 시스템에 의해 제한됩니다. 많은 수의 파일을 생성하려 할 때 EMFILE error가 발생할 수 있습니다. 이 경우 동기적 I/O의 개술를 증가시키기 위해 아래의 명령어를 수행해 보세요. -``` bash +```bash $ ulimit -n 10000 ``` @@ -37,7 +38,7 @@ $ ulimit -n 10000 If you encounter the following error: -``` bash +```bash $ ulimit -n 10000 ulimit: open files: cannot modify limit: Operation not permitted ``` @@ -48,29 +49,30 @@ To override the limit: 1. Add the following line to "/etc/security/limits.conf": - ``` - * - nofile 10000 +``` +* - nofile 10000 - # '*' applies to all users and '-' set both soft and hard limits - ``` +# '*' applies to all users and '-' set both soft and hard limits +``` - * The above setting may not apply in some cases, ensure "/etc/pam.d/login" and "/etc/pam.d/lightdm" have the following line. (Ignore this step if those files do not exist) +- The above setting may not apply in some cases, ensure "/etc/pam.d/login" and "/etc/pam.d/lightdm" have the following line. (Ignore this step if those files do not exist) - ``` - session required pam_limits.so - ``` +``` +session required pam_limits.so +``` 2. If you are on a [systemd-based](https://en.wikipedia.org/wiki/Systemd#Adoption) distribution, systemd may override "limits.conf". To set the limit in systemd, add the following line in "/etc/systemd/system.conf" and "/etc/systemd/user.conf": - ``` - DefaultLimitNOFILE=10000 - ``` +``` +DefaultLimitNOFILE=10000 +``` 3. Reboot ## `process out of memory` 생성(generation)중에 이 error가 발생할 수 있습니다.: + ``` FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory ``` @@ -85,7 +87,7 @@ FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory ## Git Deployment Problems -``` plain +```plain error: RPC failed; result=22, HTTP code = 403 fatal: 'username.github.io' does not appear to be a git repository @@ -95,19 +97,19 @@ fatal: 'username.github.io' does not appear to be a git repository ## Server Problems -``` plain +```plain Error: listen EADDRINUSE ``` 동시에 두 개의 Hexo server를 실행시키려 하거나 다른 어플리케이션이 같은 포트를 사용하려고 할 때 발생합니다. `port` 설정을 수정하거나 Hexo server를 `-p` 플래그와 함께 시작해 보세요. -``` bash +```bash $ hexo server -p 5000 ``` ## Plugin Installation Problems -``` plain +```plain npm ERR! node-waf configure build ``` @@ -142,13 +144,13 @@ Hexo는 데이터 모델로 [Warehouse]을 사용합니다. 이는 배열(array) 몇몇 데이터가 갱신되지 않거나 새로 생성되는 파일들이 마지막 버전과 동일할 경우입니다. 캐시를 정리하고 다시 시도해 보세요. -``` bash +```bash $ hexo clean ``` ## Escape Contents -Hexo는 포스트를 렌더링하는데 [Nunjucks]를 사용합니다([Swig]은 이전 버전에서 사용했었습니다. 문법은 비슷합니다.). `{{ }}` 또는 `{% %}`로 감싼 컨텐츠는 파싱된 후에 문제를 발생시킵니다. You can skip the parsing by wrapping it with the [`raw`](/docs/tag-plugins#Raw) tag plugin, single backtick ```` `{{ }}` ```` or triple backtick. +Hexo는 포스트를 렌더링하는데 [Nunjucks]를 사용합니다([Swig]은 이전 버전에서 사용했었습니다. 문법은 비슷합니다.). `{{ }}` 또는 `{% %}`로 감싼 컨텐츠는 파싱된 후에 문제를 발생시킵니다. You can skip the parsing by wrapping it with the [`raw`](/docs/tag-plugins#Raw) tag plugin, single backtick `` `{{ }}` `` or triple backtick. Alternatively, Nunjucks tags can be disabled through the renderer's option (if supported), [API](/api/renderer#Disable-Nunjucks-tags) or [front-matter](/docs/front-matter). ``` diff --git a/source/ko/docs/variables.md b/source/ko/docs/variables.md index 21af53b0ff..fce408015f 100644 --- a/source/ko/docs/variables.md +++ b/source/ko/docs/variables.md @@ -1,17 +1,18 @@ --- title: Variables --- + ### 전역 변수 -변수 | 설명 ---- | --- -`site` | 사이트 전체의 정보. -`page` | 페이지 정보와 front-matter의 사용자 정의 변수 집합. -`config` | 사이트 환경설정 -`theme` | 테마 환경설정. 사이트 환경설정을 상속합니다. -`path` | 현재 페이지의 경로 -`url` | 현재 페이지의 전체 경로 -`env` | 환경설정 변수 +| 변수 | 설명 | +| -------- | --------------------------------------------------- | +| `site` | 사이트 전체의 정보. | +| `page` | 페이지 정보와 front-matter의 사용자 정의 변수 집합. | +| `config` | 사이트 환경설정 | +| `theme` | 테마 환경설정. 사이트 환경설정을 상속합니다. | +| `path` | 현재 페이지의 경로 | +| `url` | 현재 페이지의 전체 경로 | +| `env` | 환경설정 변수 | {% note warn %} Lodash has been removed from global variables since Hexo 5.0.0. [You-Dont-Need-Lodash-Underscore](https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore) might be helpful for your migration. @@ -19,78 +20,78 @@ Lodash has been removed from global variables since Hexo 5.0.0. [You-Dont-Need-L ### 사이트 변수 -변수 | 설명 ---- | --- -`site.posts` | 모든 포스트 -`site.pages` | 모든 페이지 -`site.categories` | 모든 카테고리 -`site.tags` | 모든 태그 +| 변수 | 설명 | +| ----------------- | ------------- | +| `site.posts` | 모든 포스트 | +| `site.pages` | 모든 페이지 | +| `site.categories` | 모든 카테고리 | +| `site.tags` | 모든 태그 | ### 페이지 변수 **Article (page)** -변수 | 설명 ---- | --- -`page.title` | 게시글 제목 -`page.date` | 게시글 생성 날짜 ([Moment.js] object) -`page.updated` | 게시글이 마지막으로 갱신된 날짜 ([Moment.js] object) -`page.comments` | 코멘트를 활성화 할지 여부 -`page.layout` | 레이아웃명 -`page.content` | 게시글에서 full 처리될 컨텐츠 -`page.excerpt` | 게시글 발췌 -`page.more` | 게시글 발췌를 제외한 컨텐츠 -`page.source` | 소스 파일의 경로 -`page.full_source` | 소스 파일의 전체 경로 -`page.path` | 루트 URL을 제외한 게시글의 URL. 테마에서는 `url_for(page.path)`를 자주 사용합니다. -`page.permalink` | 게시글의 전체 URL -`page.prev` | 이전 포스트, 현재 포스트가 첫 포스트라면 `null`입니다. -`page.next` | 다음 포스트, 현재 포스트가 마지막 포스트라면 `null`입니다. -`page.raw` | 게시글의 raw 데이터 -`page.photos` | 게시글의 사진들 (Gallery post를 사용한 것들) -`page.link` | 게시글의 외부 링크 (Link post를 사용한 것들) +| 변수 | 설명 | +| ------------------ | ---------------------------------------------------------------------------------- | +| `page.title` | 게시글 제목 | +| `page.date` | 게시글 생성 날짜 ([Moment.js] object) | +| `page.updated` | 게시글이 마지막으로 갱신된 날짜 ([Moment.js] object) | +| `page.comments` | 코멘트를 활성화 할지 여부 | +| `page.layout` | 레이아웃명 | +| `page.content` | 게시글에서 full 처리될 컨텐츠 | +| `page.excerpt` | 게시글 발췌 | +| `page.more` | 게시글 발췌를 제외한 컨텐츠 | +| `page.source` | 소스 파일의 경로 | +| `page.full_source` | 소스 파일의 전체 경로 | +| `page.path` | 루트 URL을 제외한 게시글의 URL. 테마에서는 `url_for(page.path)`를 자주 사용합니다. | +| `page.permalink` | 게시글의 전체 URL | +| `page.prev` | 이전 포스트, 현재 포스트가 첫 포스트라면 `null`입니다. | +| `page.next` | 다음 포스트, 현재 포스트가 마지막 포스트라면 `null`입니다. | +| `page.raw` | 게시글의 raw 데이터 | +| `page.photos` | 게시글의 사진들 (Gallery post를 사용한 것들) | +| `page.link` | 게시글의 외부 링크 (Link post를 사용한 것들) | **Post (post):** `page` 레이아웃과 동일하지만 아래의 변수를 추가로 갖습니다. -변수 | 설명 ---- | --- -`page.published` | Post가 draft상태가 아니라면 true를 반환합니다. -`page.categories` | Post의 모든 카테고리 -`page.tags` | Post의 모든 태그 +| 변수 | 설명 | +| ----------------- | ---------------------------------------------- | +| `page.published` | Post가 draft상태가 아니라면 true를 반환합니다. | +| `page.categories` | Post의 모든 카테고리 | +| `page.tags` | Post의 모든 태그 | **Home (index)** -변수 | 설명 ---- | --- -`page.per_page` | 한 페이지에 보여질 포스트의 수 -`page.total` | 페이지의 전체 개수 -`page.current` | 현재 페이지의 번호 -`page.current_url` | 현재 페이지의 URL -`page.posts` | 이 페이지에 있는 포스트들 ([Data Model]) -`page.prev` | 이전 페이지 번호. 현재 페이지가 첫 페이지라면 `0`입니다. -`page.prev_link` | 이전 페이지의 URL. 현재 페이지가 첫 페이지라면 `''`입니다. -`page.next` | 다음 페이지 번호. 현재 페이지가 마지막 페이지라면 `0`입니다. -`page.next_link` | 다음 페이지의 URL. 현재 페이지가 마지막 페이지라면 `''`입니다. -`page.path` | 루트 URL을 제외한 현재 페이지의 URL. 테마에서는 `url_for(page.path)`를 자주 사용합니다. +| 변수 | 설명 | +| ------------------ | --------------------------------------------------------------------------------------- | +| `page.per_page` | 한 페이지에 보여질 포스트의 수 | +| `page.total` | 페이지의 전체 개수 | +| `page.current` | 현재 페이지의 번호 | +| `page.current_url` | 현재 페이지의 URL | +| `page.posts` | 이 페이지에 있는 포스트들 ([Data Model]) | +| `page.prev` | 이전 페이지 번호. 현재 페이지가 첫 페이지라면 `0`입니다. | +| `page.prev_link` | 이전 페이지의 URL. 현재 페이지가 첫 페이지라면 `''`입니다. | +| `page.next` | 다음 페이지 번호. 현재 페이지가 마지막 페이지라면 `0`입니다. | +| `page.next_link` | 다음 페이지의 URL. 현재 페이지가 마지막 페이지라면 `''`입니다. | +| `page.path` | 루트 URL을 제외한 현재 페이지의 URL. 테마에서는 `url_for(page.path)`를 자주 사용합니다. | **Archive (archive):** `index` 레이아웃과 동일하지만 아래의 변수를 추가로 갖습니다. -변수 | 설명 ---- | --- -`page.archive` | `true`와 동일합니다. -`page.year` | 아카이브 연도 (4자리 숫자) -`page.month` | 아카이브 월 (0을 제외한 2자리 숫자) +| 변수 | 설명 | +| -------------- | ----------------------------------- | +| `page.archive` | `true`와 동일합니다. | +| `page.year` | 아카이브 연도 (4자리 숫자) | +| `page.month` | 아카이브 월 (0을 제외한 2자리 숫자) | **Category (category):** `index` 레이아웃과 동일하지만 아래의 변수를 추가로 갖습니다. -변수 | 설명 ---- | --- -`page.category` | 카테고리명 +| 변수 | 설명 | +| --------------- | ---------- | +| `page.category` | 카테고리명 | **Tag (tag):** `index` 레이아웃과 동일하지만 아래의 변수를 추가로 갖습니다. -변수 | 설명 ---- | --- -`page.tag` | 태그명 +| 변수 | 설명 | +| ---------- | ------ | +| `page.tag` | 태그명 | [Moment.js]: http://momentjs.com/ diff --git a/source/ko/docs/writing.md b/source/ko/docs/writing.md index f45d0c8265..4020a269af 100644 --- a/source/ko/docs/writing.md +++ b/source/ko/docs/writing.md @@ -1,9 +1,10 @@ --- title: Writing --- + 새 포스트나 페이지를 생성하기 위해 아래 명령어를 입력하세요. -``` bash +```bash $ hexo new [layout] <title> ``` @@ -13,11 +14,11 @@ $ hexo new [layout] <title> Hexo에는 세 개의 기본 레이아웃이 존재합니다. `post`, `page`, `draft` 입니다. 이 각각의 레이아웃에 의해 생성된 파일들은 서로 다른 경로에 저장됩니다. 새롭게 생성된 포스트는 `source/_posts` 폴더에 저장됩니다. -레이아웃 | 경로 ---- | --- -`post` | `source/_posts` -`page` | `source` -`draft` | `source/_drafts` +| 레이아웃 | 경로 | +| -------- | ---------------- | +| `post` | `source/_posts` | +| `page` | `source` | +| `draft` | `source/_drafts` | {% note tip Disabling layout %} If you don't want an article (post/page) to be processed with a theme, set `layout: false` in its front-matter. Refer to [this section](/ko/docs/front-matter#레이아웃) for more details. @@ -27,20 +28,20 @@ If you don't want an article (post/page) to be processed with a theme, set `layo 기본적으로, Hexo는 post의 제목을 파일명과 동일하게 사용합니다. `_config.yml` 파일의 `new_post_name` 설정을 변경하여 기본 파일명을 바꿀 수 있습니다. 예를 들어, `:year-:month-:day-:title.md`는 포스트가 생성된 날짜를 파일명의 접두사로 사용하게 합니다. 당신은 아래와 같은 placeholder를 사용할 수 있습니다. -Placeholder | 설명 ---- | --- -`:title` | Post 제목 (소문자, 공백은 '-'하이픈으로 변경됩니다.) -`:year` | 연도를 생성합니다. 예. `2015` -`:month` | 월을 생성합니다. (0이 붙습니다.), 예. `04` -`:i_month` | 월을 생성합니다. (0이 붙지 않습니다.), 예. `4` -`:day` | 일을 생성합니다. (0이 붙습니다.), 예. `07` -`:i_day` | 일을 생성합니다. (0이 붙지 않습니다.), 예. `7` +| Placeholder | 설명 | +| ----------- | ---------------------------------------------------- | +| `:title` | Post 제목 (소문자, 공백은 '-'하이픈으로 변경됩니다.) | +| `:year` | 연도를 생성합니다. 예. `2015` | +| `:month` | 월을 생성합니다. (0이 붙습니다.), 예. `04` | +| `:i_month` | 월을 생성합니다. (0이 붙지 않습니다.), 예. `4` | +| `:day` | 일을 생성합니다. (0이 붙습니다.), 예. `07` | +| `:i_day` | 일을 생성합니다. (0이 붙지 않습니다.), 예. `7` | ### Draft 이전에, 우리는 Hexo의 특별한 레이아웃에 대해 언급한 적이 있습니다. 바로 `draft`입니다. 이 레이아웃으로 초기화된 포스트는 `source/_drafts`폴더에 저장됩니다. 당신은 `publish` 명령어를 통해 draft를 `source/_posts`폴더로 옮길 수 있습니다. `publish`는 `new` 명령어와 비슷하게 동작합니다. -``` bash +```bash $ hexo publish [layout] <title> ``` @@ -50,17 +51,17 @@ $ hexo publish [layout] <title> 포스트 생성 시 Hexo는 `scaffolds` 폴더 내의 적당한 파일을 기반으로 구성합니다. -``` bash +```bash $ hexo new photo "My Gallery" ``` 이 명령어가 수행되면 Hexo는 `scaffolds` 폴더 내에서 `photo.md`를 찾기 시작하고 이를 기반으로 한 포스트를 구성합니다. Scaffolds 내에서는 아래의 placeholder를 사용할 수 있습니다. -Placeholder | 설명 ---- | --- -`layout` | 레이아웃 -`title` | 제목 -`date` | 파일 생성일 +| Placeholder | 설명 | +| ----------- | ----------- | +| `layout` | 레이아웃 | +| `title` | 제목 | +| `date` | 파일 생성일 | ### Supported Formats diff --git a/source/plugins/index.md b/source/plugins/index.md index 2d60fa3e21..083e2285ff 100644 --- a/source/plugins/index.md +++ b/source/plugins/index.md @@ -1,3 +1,4 @@ +--- layout: plugins title: Plugins data: plugins diff --git a/source/pt-br/api/box.md b/source/pt-br/api/box.md index 30631b6c34..cb188d7601 100644 --- a/source/pt-br/api/box.md +++ b/source/pt-br/api/box.md @@ -8,12 +8,12 @@ Box é um container usado para processar arquivos em um diretório específico. O Box fornece dois métodos para carregar arquivos: `process` e `watch`. `process` carrega todos os arquivos no diretório. `watch` faz o mesmo, mas também começa a assistir as mudanças nos arquivos. -``` js -box.process().then(function(){ +```js +box.process().then(function () { // ... }); -box.watch().then(function(){ +box.watch().then(function () { // You can call box.unwatch() later to stop watching. }); ``` @@ -22,7 +22,7 @@ box.watch().then(function(){ O Box fornece muitas maneiras para a correspondência de caminho. Você pode usar uma expressão regular, uma função ou uma string no padrão Express-style. Por exemplo: -``` plain +```plain posts/:id => posts/89 posts/*path => posts/2015/title ``` @@ -33,30 +33,30 @@ Veja [util.Pattern] para mais informações. Um `processor` é um elemento essencial do Box e é usado para processar arquivos. Você pode usar o path matching conforme descrito acima para restringir o que exatamente o `processor` deve processar. Registre um novo `processor` com o método `addProcessor`. -``` js -box.addProcessor('posts/:id', function(file){ +```js +box.addProcessor("posts/:id", function (file) { // }); ``` O Box passa o conteúdo dos arquivos correspondentes aos processadores. Esta informação pode então ser lida diretamente do argumento `file` no retorno do callback: -Atributo | Descrição ---- | --- -`source` | Caminho completo do arquivo. -`path` | Caminho relativo para o Box do arquivo. -`type` | Tipo de arquivo. O valor pode ser `create`, `update`, `skip` ou `delete`. -`params` | A informação do caminho correspondente. +| Atributo | Descrição | +| -------- | ------------------------------------------------------------------------- | +| `source` | Caminho completo do arquivo. | +| `path` | Caminho relativo para o Box do arquivo. | +| `type` | Tipo de arquivo. O valor pode ser `create`, `update`, `skip` ou `delete`. | +| `params` | A informação do caminho correspondente. | O Box também fornece alguns métodos para que você não precise fazer o IO (entrada e saída) de arquivo por conta própria. -Método | Descrição ---- | --- -`read` | Ler um arquivo. -`readSync` | Ler um arquivo de forma síncrona. -`stat` | Ler o status de um arquivo. -`statSync` | Ler o status de um arquivo de forma síncrona. -`render` | Renderizar um arquivo. -`renderSync` | Renderizar um arquivo de forma síncrona. +| Método | Descrição | +| ------------ | --------------------------------------------- | +| `read` | Ler um arquivo. | +| `readSync` | Ler um arquivo de forma síncrona. | +| `stat` | Ler o status de um arquivo. | +| `statSync` | Ler o status de um arquivo de forma síncrona. | +| `render` | Renderizar um arquivo. | +| `renderSync` | Renderizar um arquivo de forma síncrona. | [util.Pattern]: https://github.com/hexojs/hexo-util#patternrule diff --git a/source/pt-br/api/console.md b/source/pt-br/api/console.md index baf9f55207..ded347bf44 100644 --- a/source/pt-br/api/console.md +++ b/source/pt-br/api/console.md @@ -6,17 +6,17 @@ O `console` forma a ponte entre o Hexo e os usuários. Ele registra e descreve o ## Resumo -``` js -hexo.extend.console.register(name, desc, options, function(args){ +```js +hexo.extend.console.register(name, desc, options, function (args) { // ... }); ``` -Argumento | Descrição ---- | --- -`name` | Nome -`desc` | Descrição -`options`| Opções +| Argumento | Descrição | +| --------- | --------- | +| `name` | Nome | +| `desc` | Descrição | +| `options` | Opções | Um argumento `args` será passado para a função. Este é o argumento que os usuários digitam no terminal. Ele é analisado pelo [Minimist]. @@ -26,8 +26,10 @@ Um argumento `args` será passado para a função. Este é o argumento que os us O uso de um comando de terminal. Por exemplo: -``` js -{usage: '[layout] <title>'} +```js +{ + usage: "[layout] <title>"; +} // hexo new [layout] <title> ``` @@ -35,12 +37,12 @@ O uso de um comando de terminal. Por exemplo: A descrição de cada argumento de um comando de terminal. Por exemplo: -``` js +```js { arguments: [ - {name: 'layout', desc: 'Post layout'}, - {name: 'title', desc: 'Post title'} - ] + { name: "layout", desc: "Post layout" }, + { name: "title", desc: "Post title" }, + ]; } ``` @@ -48,11 +50,9 @@ A descrição de cada argumento de um comando de terminal. Por exemplo: A descrição de cada opção de um comando de terminal. Por exemplo: -``` js +```js { - options: [ - {name: '-r, --replace', desc: 'Replace existing files'} - ] + options: [{ name: "-r, --replace", desc: "Replace existing files" }]; } ``` @@ -62,10 +62,14 @@ Informações mais detalhadas sobre um comando de terminal. ## Exemplo -``` js -hexo.extend.console.register('config', 'Display configuration', function(args){ - console.log(hexo.config); -}); +```js +hexo.extend.console.register( + "config", + "Display configuration", + function (args) { + console.log(hexo.config); + }, +); ``` [Minimist]: https://github.com/substack/minimist diff --git a/source/pt-br/api/deployer.md b/source/pt-br/api/deployer.md index 6b0ad60db7..733a729ad8 100644 --- a/source/pt-br/api/deployer.md +++ b/source/pt-br/api/deployer.md @@ -6,8 +6,8 @@ Um `deployer` ajuda os usuários a implantar o seu site rapidamente em um servid ## Resumo -``` js -hexo.extend.deployer.register(name, function(args){ +```js +hexo.extend.deployer.register(name, function (args) { // ... }); ``` diff --git a/source/pt-br/api/events.md b/source/pt-br/api/events.md index 9efd879ba1..7b4e50c224 100644 --- a/source/pt-br/api/events.md +++ b/source/pt-br/api/events.md @@ -28,16 +28,16 @@ Emitido depois da geração finalizada. Emitido depois de uma nova postagem ter sido criada. Este evento retorna os dados da postagem: -``` js -hexo.on('new', function(post){ +```js +hexo.on("new", function (post) { // }); ``` -Dados | Descrição ---- | --- -`post.path` | Caminho completo do arquivo da postagem -`post.content` | Conteúdo do arquivo da postagem +| Dados | Descrição | +| -------------- | --------------------------------------- | +| `post.path` | Caminho completo do arquivo da postagem | +| `post.content` | Conteúdo do arquivo da postagem | ### processBefore diff --git a/source/pt-br/api/filter.md b/source/pt-br/api/filter.md index b340c70100..a178137e7e 100644 --- a/source/pt-br/api/filter.md +++ b/source/pt-br/api/filter.md @@ -6,7 +6,7 @@ Um `filter` (filtro) pode ser utilizado para modificar alguns dados. O Hexo pass ## Resumo -``` js +```js hexo.extend.filter.register(type, function() { // User configuration const { config } = this; @@ -23,69 +23,69 @@ Você pode definir uma prioridade específica para cada filtro (parâmetro `prio ## Executar Filtros -``` js +```js hexo.extend.filter.exec(type, data, options); hexo.extend.filter.execSync(type, data, options); ``` -Opção | Descrição ---- | --- -`context` | Contexto -`args` | Argumentos. Deve ser um array. +| Opção | Descrição | +| --------- | ------------------------------ | +| `context` | Contexto | +| `args` | Argumentos. Deve ser um array. | O primeiro argumento passado para cada filtro é `data`. O próximo filtro da sequência pode receber o argumento `data` modificado ao se retornar um novo valor. Se nada for retornado, `data` continua intacto. Você ainda pode utilizar `args` para especificar outros argumentos dentro dos filtros. Por exemplo: -``` js -hexo.extend.filter.register('test', function(data, arg1, arg2){ +```js +hexo.extend.filter.register("test", function (data, arg1, arg2) { // data === 'some data' // arg1 === 'foo' // arg2 === 'bar' - return 'something'; + return "something"; }); -hexo.extend.filter.register('test', function(data, arg1, arg2){ +hexo.extend.filter.register("test", function (data, arg1, arg2) { // data === 'something' }); -hexo.extend.filter.exec('test', 'some data', { - args: ['foo', 'bar'] +hexo.extend.filter.exec("test", "some data", { + args: ["foo", "bar"], }); ``` Você também pode utilizar os seguintes métodos para executar filtros: -``` js +```js hexo.execFilter(type, data, options); hexo.execFilterSync(type, data, options); ``` ## Remover Filtros -``` js +```js hexo.extend.filter.unregister(type, filter); ``` **Example** -``` js +```js // Unregister a filter which is registered with named function const filterFn = (data) => { - data = 'something'; + data = "something"; return data; }; -hexo.extend.filter.register('example', filterFn); +hexo.extend.filter.register("example", filterFn); -hexo.extend.filter.unregister('example', filterFn); +hexo.extend.filter.unregister("example", filterFn); ``` -``` js +```js // Unregister a filter which is registered with commonjs module -hexo.extend.filter.register('example', require('path/to/filter')); +hexo.extend.filter.register("example", require("path/to/filter")); -hexo.extend.filter.unregister('example', require('path/to/filter')); +hexo.extend.filter.unregister("example", require("path/to/filter")); ``` ## Lista de Filtros @@ -98,8 +98,8 @@ Executado antes de uma postagem ser renderizada. Verificar a seção [Renderizar Por exemplo, para se transformar um título em _caixa baixa_: -``` js -hexo.extend.filter.register('before_post_render', function(data){ +```js +hexo.extend.filter.register("before_post_render", function (data) { data.title = data.title.toLowerCase(); return data; }); @@ -111,9 +111,12 @@ Executado após a postagem ser renderizado. Verificar a seção [Renderizar](pos Por exemplo, para substituir `@username` por um link para o perfil do Twitter: -``` js -hexo.extend.filter.register('after_post_render', function(data){ - data.content = data.content.replace(/@(\d+)/, '<a href="http://twitter.com/$1">#$1</a>'); +```js +hexo.extend.filter.register("after_post_render", function (data) { + data.content = data.content.replace( + /@(\d+)/, + '<a href="http://twitter.com/$1">#$1</a>', + ); return data; }); ``` @@ -122,8 +125,8 @@ hexo.extend.filter.register('after_post_render', function(data){ Executado quando o Hexo está prestes a ser terminado -- isso será executado logo após `hexo.exit` ser chamado. -``` js -hexo.extend.filter.register('before_exit', function(){ +```js +hexo.extend.filter.register("before_exit", function () { // ... }); ``` @@ -132,8 +135,8 @@ hexo.extend.filter.register('before_exit', function(){ Executado antes do processo de geração ser iniciado. -``` js -hexo.extend.filter.register('before_generate', function(){ +```js +hexo.extend.filter.register("before_generate", function () { // ... }); ``` @@ -142,8 +145,8 @@ hexo.extend.filter.register('before_generate', function(){ Executado após o processo de geração ser concluído. -``` js -hexo.extend.filter.register('after_generate', function(){ +```js +hexo.extend.filter.register("after_generate", function () { // ... }); ``` @@ -154,8 +157,8 @@ Modifica as [variáveis locais](../docs/variables.html) nos templates. Por exemplo, para adicionar a hora atual às variáveis locais dos templates: -``` js -hexo.extend.filter.register('template_locals', function(locals){ +```js +hexo.extend.filter.register("template_locals", function (locals) { locals.now = Date.now(); return locals; }); @@ -165,8 +168,8 @@ hexo.extend.filter.register('template_locals', function(locals){ Executado após a inicialização do Hexo -- este será executado logo após `hexo.init` ser concluído. -``` js -hexo.extend.filter.register('after_init', function(){ +```js +hexo.extend.filter.register("after_init", function () { // ... }); ``` @@ -175,8 +178,8 @@ hexo.extend.filter.register('after_init', function(){ Executado ao criar uma postagem para determinar o caminho das novas postagens. -``` js -hexo.extend.filter.register('new_post_path', function(data, replace){ +```js +hexo.extend.filter.register("new_post_path", function (data, replace) { // ... }); ``` @@ -185,8 +188,8 @@ hexo.extend.filter.register('new_post_path', function(data, replace){ Usado para determinar os links permanentes das postagens. -``` js -hexo.extend.filter.register('post_permalink', function(data){ +```js +hexo.extend.filter.register("post_permalink", function (data) { // ... }); ``` @@ -199,8 +202,8 @@ Executado após a renderização ser terminada. Mais informações podem ser enc Executados após os arquivos serem gerados e o cache ser removido com o comando `hexo clean`. -``` js -hexo.extend.filter.register('after_clean', function(){ +```js +hexo.extend.filter.register("after_clean", function () { // remove some other temporary files }); ``` @@ -211,10 +214,10 @@ Adiciona um middleware ao servidor. `app` é uma instância de [Connect]. Por exemplo, para adicionar `X-Powered-By: Hexo` ao cabeçalho de resposta: -``` js -hexo.extend.filter.register('server_middleware', function(app){ - app.use(function(req, res, next){ - res.setHeader('X-Powered-By', 'Hexo'); +```js +hexo.extend.filter.register("server_middleware", function (app) { + app.use(function (req, res, next) { + res.setHeader("X-Powered-By", "Hexo"); next(); }); }); diff --git a/source/pt-br/api/generator.md b/source/pt-br/api/generator.md index 07146f35ba..a2e816261b 100644 --- a/source/pt-br/api/generator.md +++ b/source/pt-br/api/generator.md @@ -6,8 +6,8 @@ Um `generator` constrói rotas a partir de arquivos processados. ## Resumo -``` js -hexo.extend.generator.register(name, function(locals){ +```js +hexo.extend.generator.register(name, function (locals) { // ... }); ``` @@ -16,27 +16,27 @@ Um argumento `locals` será passado para dentro da função, contendo as [variá ## Atualizar Rotas -``` js -hexo.extend.generator.register('test', function(locals){ +```js +hexo.extend.generator.register("test", function (locals) { // Object return { - path: 'foo', - data: 'foo' + path: "foo", + data: "foo", }; // Array return [ - {path: 'foo', data: 'foo'}, - {path: 'bar', data: 'bar'} + { path: "foo", data: "foo" }, + { path: "bar", data: "bar" }, ]; }); ``` -Atributo | Descrição ---- | --- -`path` | Caminho, sem incluir o prefixo `/`. -`data` | Dados -`layout` | Layout. Especifica os layouts para renderização. O valor pode ser uma string ou um array. Se ignorado, a rota retornará `data` diretamente. +| Atributo | Descrição | +| -------- | ------------------------------------------------------------------------------------------------------------------------------------------- | +| `path` | Caminho, sem incluir o prefixo `/`. | +| `data` | Dados | +| `layout` | Layout. Especifica os layouts para renderização. O valor pode ser uma string ou um array. Se ignorado, a rota retornará `data` diretamente. | Quando os arquivos fonte são atualizados, o Hexo executará todos os geradores e recriará as rotas. **Atenção: Retornar os dados em vez de acessar o roteador diretamente!** @@ -48,13 +48,13 @@ Crie uma página de arquivo em `archives/index.html`. Iremos passar uma lista co Após isso, defina o atributo `layout` para renderizar a página com os templates do tema. Nesse exemplo são definidos dois layouts: se o layout de `archive` não existir, o layout de `index` será utilizado em seu lugar. -``` js -hexo.extend.generator.register('archive', function(locals){ +```js +hexo.extend.generator.register("archive", function (locals) { return { - path: 'archives/index.html', + path: "archives/index.html", data: locals, - layout: ['archive', 'index'] - } + layout: ["archive", "index"], + }; }); ``` @@ -62,15 +62,15 @@ hexo.extend.generator.register('archive', function(locals){ Você pode utilizar uma ótima ferramenta oficial chamada [hexo-pagination] para criar facilmente uma página de arquivos com paginação. -``` js -var pagination = require('hexo-pagination'); +```js +var pagination = require("hexo-pagination"); -hexo.extend.generator.register('archive', function(locals){ +hexo.extend.generator.register("archive", function (locals) { // hexo-pagination makes an index.html for the /archives route - return pagination('archives', locals.posts, { + return pagination("archives", locals.posts, { perPage: 10, - layout: ['archive', 'index'], - data: {} + layout: ["archive", "index"], + data: {}, }); }); ``` @@ -79,13 +79,13 @@ hexo.extend.generator.register('archive', function(locals){ Percorra a lista de postagens em `locals.posts` e crie rotas para cada um. -``` js -hexo.extend.generator.register('post', function(locals){ - return locals.posts.map(function(post){ +```js +hexo.extend.generator.register("post", function (locals) { + return locals.posts.map(function (post) { return { path: post.path, data: post, - layout: 'post' + layout: "post", }; }); }); @@ -95,15 +95,15 @@ hexo.extend.generator.register('post', function(locals){ Dessa vez não iremos retornar `data` explicitamente, mas atribuir uma função para que a rota construa `fs.ReadStream` apenas quando necessário. -``` js -var fs = require('hexo-fs'); +```js +var fs = require("hexo-fs"); -hexo.extend.generator.register ('asset', function(locals){ +hexo.extend.generator.register("asset", function (locals) { return { - path: 'file.txt', - data: function(){ - return fs.createReadStream('path/to/file.txt') - } + path: "file.txt", + data: function () { + return fs.createReadStream("path/to/file.txt"); + }, }; }); ``` diff --git a/source/pt-br/api/helper.md b/source/pt-br/api/helper.md index e3291ffd88..9f7323ed5e 100644 --- a/source/pt-br/api/helper.md +++ b/source/pt-br/api/helper.md @@ -8,21 +8,21 @@ Os Helpers não podem ser acessados nos arquivos de `source`. ## Resumo -``` js -hexo.extend.helper.register(name, function(){ +```js +hexo.extend.helper.register(name, function () { // ... }); ``` ## Exemplo -``` js -hexo.extend.helper.register('js', function(path){ +```js +hexo.extend.helper.register("js", function (path) { return '<script src="' + path + '"></script>'; }); ``` -``` js +```js <%- js('script.js') %> // <script src="script.js"></script> ``` @@ -37,8 +37,8 @@ Place it under `scripts/` or `themes/<yourtheme>/scripts/` folder. All helpers are executed in the same context. For example, to use [`url_for()`](/docs/helpers#url-for) inside a custom helper: -``` js -hexo.extend.helper.register('lorem', function(path) { +```js +hexo.extend.helper.register("lorem", function (path) { return '<script src="' + this.url_for(path) + '"></script>'; }); ``` @@ -47,6 +47,6 @@ hexo.extend.helper.register('lorem', function(path) { `hexo.extend.helper.get` will return the helper function, but it needs to have hexo as its context, so: -``` js -const url_for = hexo.extend.helper.get('url_for').bind(hexo); +```js +const url_for = hexo.extend.helper.get("url_for").bind(hexo); ``` diff --git a/source/pt-br/api/index.md b/source/pt-br/api/index.md index 1a1a32febe..e3f7d2460f 100644 --- a/source/pt-br/api/index.md +++ b/source/pt-br/api/index.md @@ -10,21 +10,21 @@ Por favor, note que essa documentação é válida apenas para o Hexo 3 ou super Primeiro, temos que criar uma instancia do Hexo. Uma nova instancia recebe dois argumentos: o diretório raiz do site, `base_dir`, e um objeto com as opções de inicialização. Em seguida, inicializamos essa instância chamando o método `init`, que irá carregar as configurações e plugins do Hexo. -``` js -var Hexo = require('hexo'); +```js +var Hexo = require("hexo"); var hexo = new Hexo(process.cwd(), {}); -hexo.init().then(function(){ +hexo.init().then(function () { // ... }); ``` -Opção | Descrição | Padrão ---- | --- | --- -`debug` | Habilita o modo debug. Mostra as mensagens de debug no terminal e cria o arquivo `debug.log` no diretório raiz. | `false` -`safe` | Habilita o modo seguro. Não carrega nenhum plugin. | `false` -`silent` | Habilita o modo silencioso. Não mostra nenhuma mensagem no terminal. | `false` -`config` | Especifica o caminho do arquivo de configuração. | `_config.yml` +| Opção | Descrição | Padrão | +| -------- | --------------------------------------------------------------------------------------------------------------- | ------------- | +| `debug` | Habilita o modo debug. Mostra as mensagens de debug no terminal e cria o arquivo `debug.log` no diretório raiz. | `false` | +| `safe` | Habilita o modo seguro. Não carrega nenhum plugin. | `false` | +| `silent` | Habilita o modo silencioso. Não mostra nenhuma mensagem no terminal. | `false` | +| `config` | Especifica o caminho do arquivo de configuração. | `_config.yml` | ## Carregar Arquivos @@ -32,12 +32,12 @@ O Hexo fornece dois métodos para carregar arquivos: `load` e `watch`. O método Ambos os métodos irão carregar a lista de arquivos e passá-los para os processadores correspondentes. Depois de todos os arquivos terem sido processados, eles irão chamar os geradores para criar as rotas. -``` js -hexo.load().then(function(){ +```js +hexo.load().then(function () { // ... }); -hexo.watch().then(function(){ +hexo.watch().then(function () { // You can call hexo.unwatch() later to stop watching. }); ``` @@ -46,8 +46,8 @@ hexo.watch().then(function(){ Qualquer comando de console pode ser chamado explicitamente usando o método `call` na instancia do Hexo. Cada chamada recebe dois argumentos: o nome do comando do console, e um argumento de opções. Existem diferentes opções disponíveis para os diferentes comandos. -``` js -hexo.call('generate', {}).then(function(){ +```js +hexo.call("generate", {}).then(function () { // ... }); ``` @@ -56,10 +56,13 @@ hexo.call('generate', {}).then(function(){ Você deve chamar o método `exit` após a conclusão bem sucedida ou mal sucedida de um comando. Isso permite que o Hexo saia e termine coisas importantes, como salvar o banco de dados. -``` js -hexo.call('generate').then(function(){ - return hexo.exit(); -}).catch(function(err){ - return hexo.exit(err); -}); +```js +hexo + .call("generate") + .then(function () { + return hexo.exit(); + }) + .catch(function (err) { + return hexo.exit(err); + }); ``` diff --git a/source/pt-br/api/injector.md b/source/pt-br/api/injector.md index 04f45be3ce..c44a869b40 100644 --- a/source/pt-br/api/injector.md +++ b/source/pt-br/api/injector.md @@ -7,7 +7,7 @@ An injector is used to add static code snippet to the `<head>` or/and `<body>` o ## Synopsis ```js -hexo.extend.injector.register(entry, value, to) +hexo.extend.injector.register(entry, value, to); ``` ### entry `<string>` @@ -40,24 +40,34 @@ Which page will code snippets being injected. - `tag`: Only inject to tag pages (which has `is_tag()` helper being `true`) - Custom layout name could be used as well, see [Writing - Layout](writing#Layout). ----- +--- There are other internal functions, see [hexojs/hexo#4049](https://github.com/hexojs/hexo/pull/4049) for more details. ## Example ```js -const css = hexo.extend.helper.get('css').bind(hexo); -const js = hexo.extend.helper.get('js').bind(hexo); - -hexo.extend.injector.register('head_end', () => { - return css('https://cdn.jsdelivr.net/npm/aplayer@1.10.1/dist/APlayer.min.css'); -}, 'music'); - -hexo.extend.injector.register('body_end', '<script src="https://cdn.jsdelivr.net/npm/aplayer@1.10.1/dist/APlayer.min.js">', 'music'); - -hexo.extend.injector.register('body_end', () => { - return js('/js/jquery.js'); +const css = hexo.extend.helper.get("css").bind(hexo); +const js = hexo.extend.helper.get("js").bind(hexo); + +hexo.extend.injector.register( + "head_end", + () => { + return css( + "https://cdn.jsdelivr.net/npm/aplayer@1.10.1/dist/APlayer.min.css", + ); + }, + "music", +); + +hexo.extend.injector.register( + "body_end", + '<script src="https://cdn.jsdelivr.net/npm/aplayer@1.10.1/dist/APlayer.min.js">', + "music", +); + +hexo.extend.injector.register("body_end", () => { + return js("/js/jquery.js"); }); ``` @@ -69,10 +79,10 @@ Use any of the following options: 1. -``` js -const css = hexo.extend.helper.get('css').bind(hexo); +```js +const css = hexo.extend.helper.get("css").bind(hexo); -hexo.extend.injector.register('head_end', () => { +hexo.extend.injector.register("head_end", () => { const { cssPath } = hexo.config.fooPlugin; return css(cssPath); }); @@ -80,23 +90,23 @@ hexo.extend.injector.register('head_end', () => { 2. -``` js index.js +```js index.js /* global hexo */ -hexo.extend.injector.register('head_end', require('./lib/inject').bind(hexo)) +hexo.extend.injector.register("head_end", require("./lib/inject").bind(hexo)); ``` -``` js lib/inject.js +```js lib/inject.js module.exports = function () { - const css = this.extend.helper.get('css'); + const css = this.extend.helper.get("css"); const { cssPath } = this.config.fooPlugin; return css(cssPath); -} +}; ``` -``` js lib/inject.js +```js lib/inject.js function injectFn() { - const css = this.extend.helper.get('css'); + const css = this.extend.helper.get("css"); const { cssPath } = this.config.fooPlugin; return css(cssPath); } @@ -106,23 +116,23 @@ module.exports = injectFn; 3. -``` js index.js +```js index.js /* global hexo */ -hexo.extend.injector.register('head_end', require('./lib/inject')(hexo)) +hexo.extend.injector.register("head_end", require("./lib/inject")(hexo)); ``` -``` js lib/inject.js +```js lib/inject.js module.exports = (hexo) => () => { - const css = hexo.extend.helper.get('css').bind(hexo); + const css = hexo.extend.helper.get("css").bind(hexo); const { cssPath } = hexo.config.fooPlugin; return css(cssPath); }; ``` -``` js lib/inject.js +```js lib/inject.js const injectFn = (hexo) => { - const css = hexo.extend.helper.get('css').bind(hexo); + const css = hexo.extend.helper.get("css").bind(hexo); const { cssPath } = hexo.config.fooPlugin; return css(cssPath); }; diff --git a/source/pt-br/api/locals.md b/source/pt-br/api/locals.md index bba46249b2..1c08897a16 100644 --- a/source/pt-br/api/locals.md +++ b/source/pt-br/api/locals.md @@ -6,22 +6,22 @@ As variáveis locais são usadas para renderização de template, que é a vari ## Variáveis Padrão -Variável | Descrição ---- | --- -`posts` | Todas as postagens -`pages` | Todas as páginas -`categories` | Todas as categorias -`tags` | Todas as tags +| Variável | Descrição | +| ------------ | ------------------- | +| `posts` | Todas as postagens | +| `pages` | Todas as páginas | +| `categories` | Todas as categorias | +| `tags` | Todas as tags | ## Obter uma Variável -``` js -hexo.locals.get('posts') +```js +hexo.locals.get("posts"); ``` ## Atribuir uma Variável -``` js +```js hexo.locals.set('posts', function(){ return ... }); @@ -29,18 +29,18 @@ hexo.locals.set('posts', function(){ ## Remover uma Variável -``` js -hexo.locals.remove('posts'); +```js +hexo.locals.remove("posts"); ``` ## Obter Todos as Variáveis -``` js +```js hexo.locals.toObject(); ``` ## Invalidar o Cache -``` js +```js hexo.locals.invalidate(); ``` diff --git a/source/pt-br/api/migrator.md b/source/pt-br/api/migrator.md index e80083264f..95e1064b27 100644 --- a/source/pt-br/api/migrator.md +++ b/source/pt-br/api/migrator.md @@ -6,8 +6,8 @@ Um `migrator` ajuda os usuários a migrarem seus sistemas para o Hexo. ## Sinopse -``` js -hexo.extend.migrator.register(name, function(args){ +```js +hexo.extend.migrator.register(name, function (args) { // ... }); ``` diff --git a/source/pt-br/api/posts.md b/source/pt-br/api/posts.md index fbc827a174..0fed3711a7 100644 --- a/source/pt-br/api/posts.md +++ b/source/pt-br/api/posts.md @@ -4,53 +4,53 @@ title: Postagens ## Criar uma Postagem -``` js +```js hexo.post.create(data, replace); ``` -Argumento | Descrição ---- | --- -`data` | Dados -`replace` | Substitui arquivos existentes +| Argumento | Descrição | +| --------- | ----------------------------- | +| `data` | Dados | +| `replace` | Substitui arquivos existentes | Os atributos de uma postagem podem ser definidos em `data`. A tabela abaixo inclui as informações mais importantes. Atributos adicionais podem vir a ser adicionados no [front-matter](front-matter.html). -Variável | Descrição ---- | --- -`title` | Título -`slug` | URL -`layout` | Layout. Usa a configuração `default_layout` como padrão. -`path` | Caminho. Por padrão, o Hexo constrói o caminho da postagem de acordo com a definição `new_post_path`. -`date` | Data. Utiliza a data atual como padrão. +| Variável | Descrição | +| -------- | ----------------------------------------------------------------------------------------------------- | +| `title` | Título | +| `slug` | URL | +| `layout` | Layout. Usa a configuração `default_layout` como padrão. | +| `path` | Caminho. Por padrão, o Hexo constrói o caminho da postagem de acordo com a definição `new_post_path`. | +| `date` | Data. Utiliza a data atual como padrão. | ## Publicar um Rascunho -``` js +```js hexo.post.publish(data, replace); ``` -Argumento | Descrição ---- | --- -`data` | Dados -`replace` | Substitui arquivos existentes +| Argumento | Descrição | +| --------- | ----------------------------- | +| `data` | Dados | +| `replace` | Substitui arquivos existentes | Os atributos de uma postagem podem ser definidos em `data`. A tabela abaixo inclui as informações mais importantes. Atributos adicionais podem vir a ser adicionados no front-matter. -Dados | Descrição ---- | --- -`slug` | Nome do arquivo (Campo obrigatório) -`layout` | Layout. Usa a definição `default_layout` como padrão. +| Dados | Descrição | +| -------- | ----------------------------------------------------- | +| `slug` | Nome do arquivo (Campo obrigatório) | +| `layout` | Layout. Usa a definição `default_layout` como padrão. | ## Renderizar -``` js +```js hexo.post.render(source, data); ``` -Argumento | Descrição ---- | --- -`source` | Caminho completo de um arquivo (Opcional) -`data` | Dados +| Argumento | Descrição | +| --------- | ----------------------------------------- | +| `source` | Caminho completo de um arquivo (Opcional) | +| `data` | Dados | O argumento `data` deve conter o atributo `content`. Caso não inclua, o Hexo tentará carregar o arquivo inicial. As etapas de execução dessa função são listadas abaixo: diff --git a/source/pt-br/api/processor.md b/source/pt-br/api/processor.md index bfd50c54d7..9405d4c69e 100644 --- a/source/pt-br/api/processor.md +++ b/source/pt-br/api/processor.md @@ -6,9 +6,9 @@ Um `processor` é utilizado para processar os arquivos fontes contidos no diret ## Resumo -``` js -hexo.extend.processor.register(rule, function(file){ - // ... +```js +hexo.extend.processor.register(rule, function (file) { + // ... }); ``` diff --git a/source/pt-br/api/renderer.md b/source/pt-br/api/renderer.md index 1214df628a..430d012902 100644 --- a/source/pt-br/api/renderer.md +++ b/source/pt-br/api/renderer.md @@ -6,66 +6,80 @@ Um `renderer` é utilizado para renderizar conteúdos. ## Resumo -``` js -hexo.extend.renderer.register(name, output, function(data, options){ - // ... -}, sync); +```js +hexo.extend.renderer.register( + name, + output, + function (data, options) { + // ... + }, + sync, +); ``` -Argumento | Descrição ---- | --- -`name` | Extensão do arquivo de entrada (caixa baixa, sem o `.` inicial) -`output` | Extensão do arquivo de saída (caixa baixa, sem o `.` inicial) -`sync` | Modo de sincronização +| Argumento | Descrição | +| --------- | --------------------------------------------------------------- | +| `name` | Extensão do arquivo de entrada (caixa baixa, sem o `.` inicial) | +| `output` | Extensão do arquivo de saída (caixa baixa, sem o `.` inicial) | +| `sync` | Modo de sincronização | Dois argumentos devem ser passados para a função renderer: -Argumento | Descrição ---- | --- -`data` | Inclui dois atributos: Caminho do arquivo (`path`) e o conteúdo do arquivo (`text`). Não é necessário que `path` exista. -`option` | Opções +| Argumento | Descrição | +| --------- | ------------------------------------------------------------------------------------------------------------------------ | +| `data` | Inclui dois atributos: Caminho do arquivo (`path`) e o conteúdo do arquivo (`text`). Não é necessário que `path` exista. | +| `option` | Opções | ## Exemplo ### Modo Assíncrono -``` js -var stylus = require('stylus'); +```js +var stylus = require("stylus"); // Callback -hexo.extend.renderer.register('styl', 'css', function(data, options, callback){ - stylus(data.text).set('filename', data.path).render(callback); -}); +hexo.extend.renderer.register( + "styl", + "css", + function (data, options, callback) { + stylus(data.text).set("filename", data.path).render(callback); + }, +); // Promise -hexo.extend.renderer.register('styl', 'css', function(data, options){ - return new Promise(function(resolve, reject){ - resolve('test'); +hexo.extend.renderer.register("styl", "css", function (data, options) { + return new Promise(function (resolve, reject) { + resolve("test"); }); }); ``` ### Modo Síncrono -``` js -var ejs = require('ejs'); - -hexo.extend.renderer.register('ejs', 'html', function(data, options){ - options.filename = data.path; - return ejs.render(data.text, options); -}, true); +```js +var ejs = require("ejs"); + +hexo.extend.renderer.register( + "ejs", + "html", + function (data, options) { + options.filename = data.path; + return ejs.render(data.text, options); + }, + true, +); ``` ### Disable Nunjucks tags Nunjucks tags `{{ }}` or `{% %}` (utilized by [tag plugin](/docs/tag-plugins)) are processed by default, to disable: -``` js +```js function lessFn(data, options) { // do something } -lessFn.disableNunjucks = true +lessFn.disableNunjucks = true; -hexo.extend.renderer.register('less', 'css', lessFn); +hexo.extend.renderer.register("less", "css", lessFn); ``` diff --git a/source/pt-br/api/rendering.md b/source/pt-br/api/rendering.md index 3b47e37d89..70d8aea44b 100644 --- a/source/pt-br/api/rendering.md +++ b/source/pt-br/api/rendering.md @@ -6,10 +6,10 @@ Existem dois métodos para renderizar arquivos ou strings no Hexo: o método ass ## Renderizar uma String -Ao renderizar uma string, você deve especificar uma `engine` para permitir que o Hexo conheça o mecanismo de renderização que deverá ser usado. +Ao renderizar uma string, você deve especificar uma `engine` para permitir que o Hexo conheça o mecanismo de renderização que deverá ser usado. -``` js -hexo.render.render({text: 'example', engine: 'swig'}).then(function(result){ +```js +hexo.render.render({ text: "example", engine: "swig" }).then(function (result) { // ... }); ``` @@ -18,8 +18,8 @@ hexo.render.render({text: 'example', engine: 'swig'}).then(function(result){ Ao renderizar um arquivo, não é necessário especificar uma `engine` porque o Hexo detectará automaticamente o mecanismo de renderização mais apropriado com base na extensão do arquivo. Mas se for a caso, você também pode definir explicitamente a `engine`. -``` js -hexo.render.render({path: 'path/to/file.swig'}).then(function(result){ +```js +hexo.render.render({ path: "path/to/file.swig" }).then(function (result) { // ... }); ``` @@ -28,8 +28,8 @@ hexo.render.render({path: 'path/to/file.swig'}).then(function(result){ Você pode passar um conjunto de opções em formato de objeto no segundo argumento. -``` js -hexo.render.render({text: ''}, {foo: 'foo'}).then(function(result){ +```js +hexo.render.render({ text: "" }, { foo: "foo" }).then(function (result) { // ... }); ``` @@ -38,10 +38,10 @@ hexo.render.render({text: ''}, {foo: 'foo'}).then(function(result){ Quando a renderização estiver completa, o Hexo executará os filtros `after_render` correspondentes. Por exemplo, podemos usar este recurso para implementar um minificador para arquivos JavaScript. -``` js -var UglifyJS = require('uglify-js'); +```js +var UglifyJS = require("uglify-js"); -hexo.extend.filter.register('after_render:js', function(str, data){ +hexo.extend.filter.register("after_render:js", function (str, data) { var result = UglifyJS.minify(str); return result.code; }); @@ -51,30 +51,30 @@ hexo.extend.filter.register('after_render:js', function(str, data){ Você pode usar o método `isRenderable` ou `isRenderableSync` para verificar se um caminho de arquivo é renderizável. O retorno do método será `true` apenas se um renderizador correspondente for registrado. -``` js -hexo.render.isRenderable('layout.swig') // true -hexo.render.isRenderable('image.png') // false +```js +hexo.render.isRenderable("layout.swig"); // true +hexo.render.isRenderable("image.png"); // false ``` ## Obter a Extensão de Saída Use o método `getOutput` para obter a extensão da saída renderizada. Se um arquivo não foi renderizado, o método retornará uma string vazia. -``` js -hexo.render.getOutput('layout.swig') // html -hexo.render.getOutput('image.png') // ''' +```js +hexo.render.getOutput("layout.swig"); // html +hexo.render.getOutput("image.png"); // ''' ``` ## Disable Nunjucks tags If you are not using a [tag plugin](/docs/tag-plugins) and want to use `{{ }}` or `{% %}` in your post without using content [escaping](/docs/troubleshooting#Escape-Contents), you can disable processing of Nunjucks tag in existing renderer by: -``` js +```js // following example only applies to '.md' file extension // you may need to cover other extensions, e.g. '.markdown', '.mkd', etc -const renderer = hexo.render.renderer.get('md') +const renderer = hexo.render.renderer.get("md"); if (renderer) { - renderer.disableNunjucks = true - hexo.extend.renderer.register('md', 'html', renderer) + renderer.disableNunjucks = true; + hexo.extend.renderer.register("md", "html", renderer); } ``` diff --git a/source/pt-br/api/router.md b/source/pt-br/api/router.md index 1c5a79c69b..a3b06cf7ee 100644 --- a/source/pt-br/api/router.md +++ b/source/pt-br/api/router.md @@ -8,9 +8,9 @@ O `router` salva todos os caminhos usados no site. O método `get` retorna uma [Stream]. Por exemplo, para salvar os dados do caminho para um destino especificado: -``` js -var data = hexo.route.get('index.html'); -var dest = fs.createWriteStream('somewhere'); +```js +var data = hexo.route.get("index.html"); +var dest = fs.createWriteStream("somewhere"); data.pipe(dest); ``` @@ -19,32 +19,32 @@ data.pipe(dest); O método `set` recebe uma string, um [Buffer] ou uma função. -``` js +```js // String -hexo.route.set('index.html', 'index') +hexo.route.set("index.html", "index"); // Buffer -hexo.route.set('index.html', new Buffer('index')); +hexo.route.set("index.html", new Buffer("index")); // Function (Promise) -hexo.route.set('index.html', function(){ - return new Promise(function(resolve, reject){ - resolve('index'); +hexo.route.set("index.html", function () { + return new Promise(function (resolve, reject) { + resolve("index"); }); }); // Function (Callback) -hexo.route.set('index.html', function(callback){ - callback(null, 'index'); +hexo.route.set("index.html", function (callback) { + callback(null, "index"); }); ``` Você também pode definir um booleano para indicar se um caminho foi modificado ou não. Isso pode acelerar a geração de arquivos, pois permite ignorar os arquivos não modificados. -``` js -hexo.route.set('index.html', { - data: 'index', - modified: false +```js +hexo.route.set("index.html", { + data: "index", + modified: false, }); // hexo.route.isModified('index.html') => false @@ -52,13 +52,13 @@ hexo.route.set('index.html', { ## Remover um Caminho -``` js -hexo.route.remove('index.html'); +```js +hexo.route.remove("index.html"); ``` ## Obter a Lista de Rotas -``` js +```js hexo.route.list(); ``` @@ -66,8 +66,8 @@ hexo.route.list(); O método `format` transforma uma string em um caminho válido. -``` js -hexo.route.format('archives/'); +```js +hexo.route.format("archives/"); // archives/index.html ``` diff --git a/source/pt-br/api/scaffolds.md b/source/pt-br/api/scaffolds.md index 3d50be4c20..ba48d9ee40 100644 --- a/source/pt-br/api/scaffolds.md +++ b/source/pt-br/api/scaffolds.md @@ -1,20 +1,21 @@ --- title: Scaffolds --- + ## Obter um Scaffold -``` js +```js hexo.scaffold.get(name); ``` ## Definir um Scaffold -``` js +```js hexo.scaffold.set(name, content); ``` ## Remover um Scaffold -``` js +```js hexo.scaffold.remove(name); ``` diff --git a/source/pt-br/api/tag.md b/source/pt-br/api/tag.md index d9471a3243..dee6bd3e13 100644 --- a/source/pt-br/api/tag.md +++ b/source/pt-br/api/tag.md @@ -6,10 +6,14 @@ Uma tag permite que os usuários insiram, de forma rápida e fácil, snippets (t ## Resumo -``` js -hexo.extend.tag.register(name, function(args, content){ - // ... -}, options); +```js +hexo.extend.tag.register( + name, + function (args, content) { + // ... + }, + options, +); ``` Dois argumentos serão passados para dentro da função: `args` e `content`. `args` contém os argumentos passados para o tag plugin e `content` é o conteúdo envolvido do tag plugin. @@ -20,22 +24,22 @@ Desde a introdução da renderização assíncrona, na versão 3 do Hexo, estamo Use `unregister()` to replace existing [tag plugins](/docs/tag-plugins) with custom functions. -``` js +```js hexo.extend.tag.unregister(name); ``` **Example** -``` js +```js const tagFn = (args, content) => { - content = 'something'; + content = "something"; return content; }; // https://hexo.io/docs/tag-plugins#YouTube -hexo.extend.tag.unregister('youtube'); +hexo.extend.tag.unregister("youtube"); -hexo.extend.tag.register('youtube', tagFn); +hexo.extend.tag.register("youtube", tagFn); ``` ## Opções @@ -54,10 +58,14 @@ Habilite o modo assíncrono. Esta opção é `false` por padrão. Insira um vídeo do Youtube. -``` js -hexo.extend.tag.register('youtube', function(args){ +```js +hexo.extend.tag.register("youtube", function (args) { var id = args[0]; - return '<div class="video-container"><iframe width="560" height="315" src="http://www.youtube.com/embed/' + id + '" frameborder="0" allowfullscreen></iframe></div>'; + return ( + '<div class="video-container"><iframe width="560" height="315" src="http://www.youtube.com/embed/' + + id + + '" frameborder="0" allowfullscreen></iframe></div>' + ); }); ``` @@ -65,29 +73,43 @@ hexo.extend.tag.register('youtube', function(args){ Insira uma citação. -``` js -hexo.extend.tag.register('pullquote', function(args, content){ - var className = args.join(' '); - return '<blockquote class="pullquote' + className + '">' + content + '</blockquote>'; -}, {ends: true}); +```js +hexo.extend.tag.register( + "pullquote", + function (args, content) { + var className = args.join(" "); + return ( + '<blockquote class="pullquote' + + className + + '">' + + content + + "</blockquote>" + ); + }, + { ends: true }, +); ``` ### Renderização Assíncrona Insira um arquivo. -``` js -var fs = require('hexo-fs'); -var pathFn = require('path'); - -hexo.extend.tag.register('include_code', function(args){ - var filename = args[0]; - var path = pathFn.join(hexo.source_dir, filename); - - return fs.readFile(path).then(function(content){ - return '<pre><code>' + content + '</code></pre>'; - }); -}, {async: true}); +```js +var fs = require("hexo-fs"); +var pathFn = require("path"); + +hexo.extend.tag.register( + "include_code", + function (args) { + var filename = args[0]; + var path = pathFn.join(hexo.source_dir, filename); + + return fs.readFile(path).then(function (content) { + return "<pre><code>" + content + "</code></pre>"; + }); + }, + { async: true }, +); ``` ## Front-matter and user configuration @@ -96,7 +118,7 @@ Any of the following options is valid: 1. -``` js +```js hexo.extend.tag.register('foo', function (args) { const [firstArg] = args; @@ -121,11 +143,11 @@ hexo.extend.tag.register('foo', function (args) { 2. -``` js index.js -hexo.extend.tag.register('foo', require('./lib/foo')(hexo)); +```js index.js +hexo.extend.tag.register("foo", require("./lib/foo")(hexo)); ``` -``` js lib/foo.js +```js lib/foo.js module.exports = hexo => { return function fooFn(args) { const [firstArg] = args; diff --git a/source/pt-br/api/themes.md b/source/pt-br/api/themes.md index 43dede5976..07009d3ada 100644 --- a/source/pt-br/api/themes.md +++ b/source/pt-br/api/themes.md @@ -6,19 +6,19 @@ O `hexo.theme` herda de [Box](box.html) e também guarda os templates. ## Obter uma View -``` js +```js hexo.theme.getView(path); ``` ## Definir uma View -``` js +```js hexo.theme.setView(path, data); ``` ## Remover uma View -``` js +```js hexo.theme.removeView(path); ``` @@ -26,10 +26,10 @@ hexo.theme.removeView(path); As Views têm dois métodos: `render` e `renderSync`. Esses dois métodos são idênticos, mas o primeiro é assíncrono e o segundo é síncrono. Por uma questão de simplicidade, só discutiremos `render` aqui. -``` js -var view = hexo.theme.getView('layout.swig'); +```js +var view = hexo.theme.getView("layout.swig"); -view.render({foo: 1, bar: 2}).then(function(result){ +view.render({ foo: 1, bar: 2 }).then(function (result) { // ... }); ``` diff --git a/source/pt-br/docs/asset-folders.md b/source/pt-br/docs/asset-folders.md index 988af971a4..8193179922 100644 --- a/source/pt-br/docs/asset-folders.md +++ b/source/pt-br/docs/asset-folders.md @@ -1,6 +1,7 @@ --- title: Diretórios de Recursos (Asset) --- + ## Diretório Global de Recursos Os recursos, ou assets, são arquivos (imagens, CSS, JavaScript e etc) usados para compor as páginas do site. No Hexo, os recursos ficam dentro do diretório `source`. Por exemplo, se você só vai ter algumas imagens no projeto Hexo, então a maneira mais fácil é mantê-las em um diretório como `source/images`. Então, você pode acessá-las usando algo como `![](images/image.jpg)`. @@ -11,7 +12,7 @@ Os recursos, ou assets, são arquivos (imagens, CSS, JavaScript e etc) usados pa Para os usuários que esperam exibir imagens e/ou outros recursos regularmente, e para aqueles que preferem separar seus recursos por publicação, o Hexo também fornece uma maneira mais organizada de fazer este gerenciamento. Para ativar o gerenciamento de recursos por publicação, defina a configuração `post_asset_folder` no arquivo `_config.yml` como o valor `true`. -``` yaml _config.yml +```yaml _config.yml post_asset_folder: true ``` @@ -27,7 +28,7 @@ Referenciar imagens, ou outros recursos, usando a sintaxe normal do markdown e c {% asset_link slug [title] %} ``` -Por exemplo, com os diretórios de recursos de postagem ativados, se você colocar uma imagem `example.jpg` no seu diretório de recursos, ela *não* aparecerá na página de índice se você fizer referência a ela usando um caminho relativo com a expressão `![](example.jpg)` da sintaxe do markdown (no entanto, isto funcionará como esperado na publicação em si). +Por exemplo, com os diretórios de recursos de postagem ativados, se você colocar uma imagem `example.jpg` no seu diretório de recursos, ela _não_ aparecerá na página de índice se você fizer referência a ela usando um caminho relativo com a expressão `![](example.jpg)` da sintaxe do markdown (no entanto, isto funcionará como esperado na publicação em si). A maneira correta de fazer referência à imagem será usando a sintaxe de tag plugin em vez do markdown: @@ -44,7 +45,7 @@ Desta forma, a imagem aparecerá dentro da publicação e nas páginas de índic To enable: -``` yml _config.yml +```yml _config.yml post_asset_folder: true marked: prependRoot: true diff --git a/source/pt-br/docs/commands.md b/source/pt-br/docs/commands.md index ec2a5569fc..2bc16a7fb0 100644 --- a/source/pt-br/docs/commands.md +++ b/source/pt-br/docs/commands.md @@ -4,7 +4,7 @@ title: Comandos ## init -``` bash +```bash $ hexo init [folder] ``` @@ -17,30 +17,30 @@ This command is a shortcut that runs the following steps: ## new -``` bash +```bash $ hexo new [layout] <title> ``` -Cria um novo artigo. Se nenhum `layout` for fornecido, o Hexo usará o `default_layout` de [_config.yml](configuration.html). Se o `title` contiver espaços, rode-o com aspas. +Cria um novo artigo. Se nenhum `layout` for fornecido, o Hexo usará o `default_layout` de [\_config.yml](configuration.html). Se o `title` contiver espaços, rode-o com aspas. ## generate -``` bash +```bash $ hexo generate ``` Gera os arquivos estáticos. -Opção | Descrição ---- | --- -`-d`, `--deploy` | Faz o deploy após os arquivos estáticos serem gerados -`-w`, `--watch` | Assiste alterações no aquivo -`-b`, `--bail` | Levanta um erro se qualquer exceção não tratada for lançada durante o processo de geração dos arquivos -`-f`, `--force` | Regeneração forçada +| Opção | Descrição | +| ---------------- | ------------------------------------------------------------------------------------------------------ | +| `-d`, `--deploy` | Faz o deploy após os arquivos estáticos serem gerados | +| `-w`, `--watch` | Assiste alterações no aquivo | +| `-b`, `--bail` | Levanta um erro se qualquer exceção não tratada for lançada durante o processo de geração dos arquivos | +| `-f`, `--force` | Regeneração forçada | ## publish -``` bash +```bash $ hexo publish [layout] <filename> ``` @@ -48,45 +48,45 @@ Publica um rascunho. ## server -``` bash +```bash $ hexo server ``` Inicia um servidor local. Por padrão, o local é `http://localhost:4000/`. -Opção | Descrição ---- | --- -`-p`, `--port` | Substituir a porta padrão -`-s`, `--static` | Somente serve arquivos estáticos -`-l`, `--log` | Ativar o logger. Substitui o formato do logger. +| Opção | Descrição | +| ---------------- | ----------------------------------------------- | +| `-p`, `--port` | Substituir a porta padrão | +| `-s`, `--static` | Somente serve arquivos estáticos | +| `-l`, `--log` | Ativar o logger. Substitui o formato do logger. | ## deploy -``` bash +```bash $ hexo deploy ``` Implanta o site. -Opção | Descrição ---- | --- -`-g`, `--generate` | Gerar os arquivos estáticos antes do deploy +| Opção | Descrição | +| ------------------ | ------------------------------------------- | +| `-g`, `--generate` | Gerar os arquivos estáticos antes do deploy | ## render -``` bash +```bash $ hexo render <file1> [file2] ... ``` Renderiza arquivos. -Opção | Descrição ---- | --- -`-o`, `--output` | Destino de saída +| Opção | Descrição | +| ---------------- | ---------------- | +| `-o`, `--output` | Destino de saída | ## migrate -``` bash +```bash $ hexo migrate <type> ``` @@ -94,7 +94,7 @@ $ hexo migrate <type> ## clean -``` bash +```bash $ hexo clean ``` @@ -102,7 +102,7 @@ Limpa o arquivo de cache (`db.json`) e os arquivos gerados (`public`). ## list -``` bash +```bash $ hexo list <type> ``` @@ -110,7 +110,7 @@ Lista todas as rotas ## version -``` bash +```bash $ hexo version ``` @@ -120,7 +120,7 @@ Exibe informações de versão. ### Modo safe -``` bash +```bash $ hexo --safe ``` @@ -128,7 +128,7 @@ Desativa o carregamento de plugins e scripts. Tente isso se você encontrar prob ### Modo debug -``` bash +```bash $ hexo --debug ``` @@ -136,7 +136,7 @@ Registra mensagens detalhadas para o terminal e para o arquivo `debug.log`. Tent ### Modo silent -``` bash +```bash $ hexo --silent ``` @@ -144,19 +144,19 @@ Silencia a saída para no terminal. ### Caminho do arquivo de configuração personalizado -``` bash +```bash $ hexo --config custom.yml ``` Usa um arquivo de configuração personalizado (em vez de `_config.yml`). Também aceita uma lista separada por vírgulas (sem espaços) de arquivos de configuração JSON ou YAML que combinará os arquivos em um único `_multiconfig.yml`. -``` bash +```bash $ hexo --config custom.yml,custom2.json ``` ### Mostra rascunhos -``` bash +```bash $ hexo --draft ``` @@ -164,7 +164,7 @@ Exibe os rascunhos (armazenados no diretório `source/_drafts`). ### Customizando CWD -``` bash +```bash $ hexo --cwd /path/to/cwd ``` diff --git a/source/pt-br/docs/configuration.md b/source/pt-br/docs/configuration.md index 3bab759586..697f38be58 100644 --- a/source/pt-br/docs/configuration.md +++ b/source/pt-br/docs/configuration.md @@ -6,27 +6,27 @@ Você pode modificar as configurações do site em `_config.yml` ou em um [arqui ### Site -Configuração | Descrição ---- | --- -`title` | O título do seu site -`subtitle` | O subtítulo do seu site -`description` | A descrição do seu site -`keywords` | The keywords of your website. Supports multiple values. -`author` | Seu nome -`language` | O idioma do seu site. Use a [2-lettter ISO-639-1 code](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). O padrão é `en`. -`timezone` | O fuso horário do seu site. O Hexo usa a configuração do seu computador por padrão. Você pode encontrar a lista de fusos horários disponíveis [aqui](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). Alguns exemplos são `America/New_York`, `Japan` e `UTC`. +| Configuração | Descrição | +| ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `title` | O título do seu site | +| `subtitle` | O subtítulo do seu site | +| `description` | A descrição do seu site | +| `keywords` | The keywords of your website. Supports multiple values. | +| `author` | Seu nome | +| `language` | O idioma do seu site. Use a [2-lettter ISO-639-1 code](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). O padrão é `en`. | +| `timezone` | O fuso horário do seu site. O Hexo usa a configuração do seu computador por padrão. Você pode encontrar a lista de fusos horários disponíveis [aqui](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). Alguns exemplos são `America/New_York`, `Japan` e `UTC`. | ### URL -Configuração | Descrição | Padrão ---- | --- | --- -`url` | A URL do seu site, must starts with `http://` or `https://` | -`root` | O diretório raiz do seu site | `url's pathname` -`permalink` | O formato de [permalink](permalinks.html) dos artigos | `:year/:month/:day/:title/` -`permalink_defaults` | Valores padrão de cada segmento no permalink | -`pretty_urls` | Rewrite the [`permalink`](variables.html) variables to pretty URLs | -`pretty_urls.trailing_index` | Trailing `index.html`, set to `false` to remove it | `true` -`pretty_urls.trailing_html` | Trailing `.html`, set to `false` to remove it (_does not apply to trailing `index.html`_) | `true` +| Configuração | Descrição | Padrão | +| ---------------------------- | ----------------------------------------------------------------------------------------- | --------------------------- | +| `url` | A URL do seu site, must starts with `http://` or `https://` | +| `root` | O diretório raiz do seu site | `url's pathname` | +| `permalink` | O formato de [permalink](permalinks.html) dos artigos | `:year/:month/:day/:title/` | +| `permalink_defaults` | Valores padrão de cada segmento no permalink | +| `pretty_urls` | Rewrite the [`permalink`](variables.html) variables to pretty URLs | +| `pretty_urls.trailing_index` | Trailing `index.html`, set to `false` to remove it | `true` | +| `pretty_urls.trailing_html` | Trailing `.html`, set to `false` to remove it (_does not apply to trailing `index.html`_) | `true` | {% note info Site em subdiretório %} Se o seu site estiver em um subdiretório (como por exemplo `http://example.org/blog`) defina `url` para `http://example.org/blog` e defina `root` para `/blog/`. @@ -34,53 +34,53 @@ Se o seu site estiver em um subdiretório (como por exemplo `http://example.org/ ### Diretório -Configuração | Descrição | Padrão ---- | --- | --- -`source_dir` | Diretório dos fonte. Onde seu conteúdo está armazenado | `source` -`public_dir` | Diretório dos arquivos públicos. Onde o site estático será gerado | `public` -`tag_dir` | Diretório de tags | `tags` -`archive_dir` | Diretório de archives | `archives` -`category_dir` | Diretório de categorias | `categories` -`code_dir` | Diretório de código (subdiretório de `source_dir`) | `downloads/code` -`i18n_dir` | Diretório de internacionalização (i18n) | `:lang` -`skip_render` | Caminhos que não devem ser renderizados. Você pode usar [expressões globais](https://github.com/micromatch/micromatch#extended-globbing) para fazer correspondência de caminho | +| Configuração | Descrição | Padrão | +| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------- | +| `source_dir` | Diretório dos fonte. Onde seu conteúdo está armazenado | `source` | +| `public_dir` | Diretório dos arquivos públicos. Onde o site estático será gerado | `public` | +| `tag_dir` | Diretório de tags | `tags` | +| `archive_dir` | Diretório de archives | `archives` | +| `category_dir` | Diretório de categorias | `categories` | +| `code_dir` | Diretório de código (subdiretório de `source_dir`) | `downloads/code` | +| `i18n_dir` | Diretório de internacionalização (i18n) | `:lang` | +| `skip_render` | Caminhos que não devem ser renderizados. Você pode usar [expressões globais](https://github.com/micromatch/micromatch#extended-globbing) para fazer correspondência de caminho | ### Escrita -Configuração | Descrição | Padrão ---- | --- | --- -`new_post_name` | O formato do nome do arquivo para novas postagens | `:title.md` -`default_layout` | Layout padrão | `post` -`titlecase` | Transformar títulos em maiúsculo? | `false` -`external_link` | Abrir links externos em uma nova aba? -`external_link.enable` | Abrir links externos em uma nova aba? | `true` -`external_link.field` | Applies to the whole `site` or `post` only | `site` -`external_link.exclude` | Exclude hostname. Specify subdomain when applicable, including `www` | `[]` -`filename_case` | Converter nomes de arquivos para minúsculos `1`; maiúsculos `2` | `0` -`render_drafts` | Exibir rascunhos? | `false` -`post_asset_folder` | Ativar o [diretório de Asset](asset-folders.html)? | `false` -`relative_link` | Links para o diretório raiz? | `false` -`future` | Exibir postagens futuras? | `true` -`highlight` | Configurações de bloco de código, see [Highlight.js](/docs/syntax-highlight#Highlight-js) section for usage guide | -`prismjs` | Configurações de bloco de código, see [PrismJS](/docs/syntax-highlight#PrismJS) section for usage guide | +| Configuração | Descrição | Padrão | +| ----------------------- | ----------------------------------------------------------------------------------------------------------------- | ----------- | +| `new_post_name` | O formato do nome do arquivo para novas postagens | `:title.md` | +| `default_layout` | Layout padrão | `post` | +| `titlecase` | Transformar títulos em maiúsculo? | `false` | +| `external_link` | Abrir links externos em uma nova aba? | +| `external_link.enable` | Abrir links externos em uma nova aba? | `true` | +| `external_link.field` | Applies to the whole `site` or `post` only | `site` | +| `external_link.exclude` | Exclude hostname. Specify subdomain when applicable, including `www` | `[]` | +| `filename_case` | Converter nomes de arquivos para minúsculos `1`; maiúsculos `2` | `0` | +| `render_drafts` | Exibir rascunhos? | `false` | +| `post_asset_folder` | Ativar o [diretório de Asset](asset-folders.html)? | `false` | +| `relative_link` | Links para o diretório raiz? | `false` | +| `future` | Exibir postagens futuras? | `true` | +| `highlight` | Configurações de bloco de código, see [Highlight.js](/docs/syntax-highlight#Highlight-js) section for usage guide | +| `prismjs` | Configurações de bloco de código, see [PrismJS](/docs/syntax-highlight#PrismJS) section for usage guide | ### Categoria & Tag -Configuração | Descrição | Padrão ---- | --- | --- -`default_category` | Categoria padrão | `uncategorized` -`category_map` | Mapa de Categoria | -`tag_map` | Mapa de Tag | +| Configuração | Descrição | Padrão | +| ------------------ | ----------------- | --------------- | +| `default_category` | Categoria padrão | `uncategorized` | +| `category_map` | Mapa de Categoria | +| `tag_map` | Mapa de Tag | ### Formato de Data / Hora Hexo usa [Moment.js](http://momentjs.com/) para processar datas. -Configuração | Descrição | Padrão ---- | --- | --- -`date_format` | Formato de data | `YYYY-MM-DD` -`time_format` | Formado de hora | `HH:mm:ss` -`updated_option` | The [`updated`](/pt-br/docs/variables#Variaveis-da-Pagina) value to used when not provided in the front-matter | `mtime` +| Configuração | Descrição | Padrão | +| ---------------- | -------------------------------------------------------------------------------------------------------------- | ------------ | +| `date_format` | Formato de data | `YYYY-MM-DD` | +| `time_format` | Formado de hora | `HH:mm:ss` | +| `updated_option` | The [`updated`](/pt-br/docs/variables#Variaveis-da-Pagina) value to used when not provided in the front-matter | `mtime` | {% note info updated_option %} `updated_option` controls the `updated` value when not provided in the front-matter: @@ -94,19 +94,19 @@ Configuração | Descrição | Padrão ### Paginação -Configuração | Descrição | Padrão ---- | --- | --- -`per_page` | A quantidade de postagens exibidas em uma única página. `0` desabilita paginação | `10` -`pagination_dir` | Diretório de paginação | `page` +| Configuração | Descrição | Padrão | +| ---------------- | -------------------------------------------------------------------------------- | ------ | +| `per_page` | A quantidade de postagens exibidas em uma única página. `0` desabilita paginação | `10` | +| `pagination_dir` | Diretório de paginação | `page` | ### Extensões -Configuração | Descrição ---- | --- -`theme` | Nome do tema. `false` desabilita o tema -`theme_config` | Configuração do tema. Inclui quaisquer configurações de tema personalizado sob esta chave para substituir os padrões do tema. -`deploy` | Configurações de implantação -`meta_generator` | [Meta generator](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta#Attributes) tag. `false` disables injection of the tag. +| Configuração | Descrição | +| ---------------- | --------------------------------------------------------------------------------------------------------------------------------------- | +| `theme` | Nome do tema. `false` desabilita o tema | +| `theme_config` | Configuração do tema. Inclui quaisquer configurações de tema personalizado sob esta chave para substituir os padrões do tema. | +| `deploy` | Configurações de implantação | +| `meta_generator` | [Meta generator](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta#Attributes) tag. `false` disables injection of the tag. | ### Incluir/Excluir Arquivos ou Diretórios @@ -114,11 +114,11 @@ No arquivo de configuração, defina a chave de include/exclude para que o hexo `include` and `exclude` options only apply to the `source/` folder, whereas `ignore` option applies to all folders. -Configuração | Descrição ---- | --- -`include` | Por padrão, o Hexo ignora os arquivos e diretórios ocultos, mas configurar este campo fará com que o Hexo os processe também -`exclude` | O Hexo irá ignorar os arquivos e diretórios listados abaixo deste campo -`ignore` | Ignore files/folders +| Configuração | Descrição | +| ------------ | ---------------------------------------------------------------------------------------------------------------------------- | +| `include` | Por padrão, o Hexo ignora os arquivos e diretórios ocultos, mas configurar este campo fará com que o Hexo os processe também | +| `exclude` | O Hexo irá ignorar os arquivos e diretórios listados abaixo deste campo | +| `ignore` | Ignore files/folders | Exemplo: @@ -179,7 +179,7 @@ theme: "my-theme" theme_config: bio: "My awesome bio" foo: - bar: 'a' + bar: "a" ``` ```yml @@ -194,11 +194,11 @@ Resulting in theme configuration: ```json { - bio: "My awesome bio", - logo: "a-cool-image.png", - foo: { - bar: "a", - baz: "b" + "bio": "My awesome bio", + "logo": "a-cool-image.png", + "foo": { + "bar": "a", + "baz": "b" } } ``` @@ -218,7 +218,7 @@ theme: "my-theme" # _config.my-theme.yml bio: "My awesome bio" foo: - bar: 'a' + bar: "a" ``` ```yml @@ -233,11 +233,11 @@ Resulting in theme configuration: ```json { - bio: "My awesome bio", - logo: "a-cool-image.png", - foo: { - bar: "a", - baz: "b" + "bio": "My awesome bio", + "logo": "a-cool-image.png", + "foo": { + "bar": "a", + "baz": "b" } } ``` diff --git a/source/pt-br/docs/contributing.md b/source/pt-br/docs/contributing.md index 3a551297b2..18eec7a77d 100644 --- a/source/pt-br/docs/contributing.md +++ b/source/pt-br/docs/contributing.md @@ -25,7 +25,7 @@ Also, Hexo has its own [ESLint config](https://github.com/hexojs/eslint-config-h 1. Faça um fork [hexojs/hexo]. 2. Clone o repositório no seu computador e instale as dependências. -``` bash +```bash $ git clone https://github.com/<username>/hexo.git $ cd hexo $ npm install @@ -34,7 +34,7 @@ $ git submodule update --init 3. Crie um branch para a feature a ser desenvolvida. -``` bash +```bash $ git checkout -b new_feature ``` @@ -52,7 +52,7 @@ $ git push origin new_feature - Não modifique o número da versão no arquivo `package.json`. - Seu pedido de pull request só será aceito quando os testes tiverem passado. Não se esqueça de executar testes antes da submissão. -``` bash +```bash $ npm test ``` @@ -69,7 +69,7 @@ A documentação do Hexo é de código aberto e você pode encontrar o código-f 1. Faça um fork [hexojs/site] 2. Clone o repositório no seu computador e instale as dependências. -``` bash +```bash $ npm install hexo-cli -g # If you don't have hexo-cli installed $ git clone https://github.com/<username>/site.git $ cd site @@ -78,7 +78,7 @@ $ npm install 3. Comece a editar a documentação. Você pode iniciar o servidor para a visualização das mudanças em tempo real. -``` bash +```bash $ hexo server ``` diff --git a/source/pt-br/docs/data-files.md b/source/pt-br/docs/data-files.md index 2a250ff61b..874f7e20ec 100644 --- a/source/pt-br/docs/data-files.md +++ b/source/pt-br/docs/data-files.md @@ -1,13 +1,14 @@ --- title: Arquivos de Dados --- + Às vezes, você pode precisar usar alguns dados em templates que não estão diretamente disponíveis em suas postagens, ou ainda, você deseja reutilizar os dados em um outro lugar. Para esses casos de uso, o Hexo 3 introduziu os novos **Data files** (arquivos de dados). Este recurso carrega arquivos YAML ou JSON no diretório `source/_data` para que você possa usá-los em seu site. {% youtube CN31plHbI-w %} Por exemplo, adicione `menu.yml` no diretório `source/_data`. -``` yaml +```yaml Home: / Gallery: /gallery/ Archives: /archives/ diff --git a/source/pt-br/docs/front-matter.md b/source/pt-br/docs/front-matter.md index bbff1897f4..b9fd1c3e14 100644 --- a/source/pt-br/docs/front-matter.md +++ b/source/pt-br/docs/front-matter.md @@ -8,7 +8,7 @@ Front-matter é um bloco de YAML ou JSON no início do arquivo que é usado para **YAML** -``` yaml +```yaml --- title: Hello World date: 2013/7/13 20:46:25 @@ -17,7 +17,7 @@ date: 2013/7/13 20:46:25 **JSON** -``` json +```json "title": "Hello World", "date": "2013/7/13 20:46:25" ;;; @@ -25,23 +25,23 @@ date: 2013/7/13 20:46:25 ### Configurações e Seus Valores Padrão -Configuração | Descrição | Padrão ---- | --- | --- -`layout` | Layout | [`config.default_layout`](/pt-br/docs/configuration#Escrita) -`title` | Título | Filename (posts only) -`date` | Data de publicação | Data de criação do arquivo -`updated` | Data de atualização | Data de atualização do arquivo -`comments` | Habilita o recurso de comentário para a postagem | true -`tags` | Tags (Não disponível para páginas) | -`categories` | Categorias (Não disponível para páginas) | -`permalink` | Substitui o permalink padrão da postagem | -`excerpt` | Page excerpt in plain text. Use [this plugin](/docs/tag-plugins#Post-Excerpt) to format the text | -`disableNunjucks` | Disable rendering of Nunjucks tag `{{ }}`/`{% %}` and [tag plugins](/docs/tag-plugins) when enabled -`lang` | Set the language to override [auto-detection](/docs/internationalization#Path) | Inherited from `_config.yml` +| Configuração | Descrição | Padrão | +| ----------------- | --------------------------------------------------------------------------------------------------- | ------------------------------------------------------------ | +| `layout` | Layout | [`config.default_layout`](/pt-br/docs/configuration#Escrita) | +| `title` | Título | Filename (posts only) | +| `date` | Data de publicação | Data de criação do arquivo | +| `updated` | Data de atualização | Data de atualização do arquivo | +| `comments` | Habilita o recurso de comentário para a postagem | true | +| `tags` | Tags (Não disponível para páginas) | +| `categories` | Categorias (Não disponível para páginas) | +| `permalink` | Substitui o permalink padrão da postagem | +| `excerpt` | Page excerpt in plain text. Use [this plugin](/docs/tag-plugins#Post-Excerpt) to format the text | +| `disableNunjucks` | Disable rendering of Nunjucks tag `{{ }}`/`{% %}` and [tag plugins](/docs/tag-plugins) when enabled | +| `lang` | Set the language to override [auto-detection](/docs/internationalization#Path) | Inherited from `_config.yml` | #### Layout -The default layout is `post`, in accordance to the value of [`default_layout`]((/docs/configuration#Writing)) setting in `_config.yml`. When the layout is disabled (`layout: false`) in an article, it will not be processed with a theme. However, it will still be rendered by any available renderer: if an article is written in Markdown and a Markdown renderer (like the default [hexo-renderer-marked](https://github.com/hexojs/hexo-renderer-marked)) is installed, it will be rendered to HTML. +The default layout is `post`, in accordance to the value of [`default_layout`](/docs/configuration#Writing) setting in `_config.yml`. When the layout is disabled (`layout: false`) in an article, it will not be processed with a theme. However, it will still be rendered by any available renderer: if an article is written in Markdown and a Markdown renderer (like the default [hexo-renderer-marked](https://github.com/hexojs/hexo-renderer-marked)) is installed, it will be rendered to HTML. [Tag plugins](/docs/tag-plugins) are always processed regardless of layout, unless disabled by the `disableNunjucks` setting or [renderer](/api/renderer#Disable-Nunjucks-tags). @@ -51,24 +51,24 @@ Somente postagens aceitam o uso de categorias e tags. As categorias aplicam-se **Exemplo** -``` yaml +```yaml categories: -- Sports -- Baseball + - Sports + - Baseball tags: -- Injury -- Fight -- Shocking + - Injury + - Fight + - Shocking ``` Se você quiser aplicar várias hierarquias de categorias, use uma lista de nomes em vez de um único nome. Se o Hexo encontar qualquer categoria definida dessa forma em uma postagem, ele tratará cada categoria para essa postagem com sua própria hierarquia independente. **Exemplo** -``` yaml +```yaml categories: -- [Sports, Baseball] -- [MLB, American League, Boston Red Sox] -- [MLB, American League, New York Yankees] -- Rivalries + - [Sports, Baseball] + - [MLB, American League, Boston Red Sox] + - [MLB, American League, New York Yankees] + - Rivalries ``` diff --git a/source/pt-br/docs/generating.md b/source/pt-br/docs/generating.md index e93b644352..5226dd76fa 100644 --- a/source/pt-br/docs/generating.md +++ b/source/pt-br/docs/generating.md @@ -4,7 +4,7 @@ title: Gerando Gerar arquivos estáticos com o Hexo é bastante fácil e rápido. -``` bash +```bash $ hexo generate ``` @@ -14,7 +14,7 @@ $ hexo generate O Hexo pode ficar observando as alterações nos arquivos e regerar arquivos imediatamente. O hexo compara a hash (SHA1) dos seus arquivos e somente regenera aqueles que sofreram modificações. -``` bash +```bash $ hexo generate --watch ``` @@ -22,7 +22,7 @@ $ hexo generate --watch Para fazer o deploy depois de gerar os arquivos, você pode executar um dos seguintes comandos. Não há diferença entre os dois. -``` bash +```bash $ hexo generate --deploy $ hexo deploy --generate ``` diff --git a/source/pt-br/docs/github-pages.md b/source/pt-br/docs/github-pages.md index ec52a841e0..68a109dbea 100755 --- a/source/pt-br/docs/github-pages.md +++ b/source/pt-br/docs/github-pages.md @@ -4,14 +4,14 @@ title: GitHub Pages In this tutorial, we use [Travis CI](https://travis-ci.com/) to deploy Github Pages. It is free for open source repository, meaning your repository's `master` branch has to be public. Please skip to the [Private repository](#Private-repository) section if you prefer to keep the repo private, or prefer not to upload your source folder to GitHub. -1. Create a repo named <b>*username*.github.io</b>, where username is your username on GitHub. If you have already uploaded to other repo, rename the repo instead. +1. Create a repo named <b>_username_.github.io</b>, where username is your username on GitHub. If you have already uploaded to other repo, rename the repo instead. 2. Push the files of your Hexo folder to the repository. The `public/` folder is not (and should not be) uploaded by default, make sure the `.gitignore` file contains `public/` line. The folder structure should be roughly similar to [this repo](https://github.com/hexojs/hexo-starter), without the `.gitmodules` file. 3. Add [Travis CI](https://github.com/marketplace/travis-ci) to your account. 4. Go to [Applications settings](https://github.com/settings/installations), configure Travis CI to have access to the repo. 5. You'll be redirected to Travis page. 6. On a new tab, generate a [new token](https://github.com/settings/tokens) with **repo** scopes. Note down the token value. 7. On the Travis page, go to your repo's setting. Under **Environment Variables**, put **GH_TOKEN** as name and paste the token onto value. Click Add to save it. -8. Add `.travis.yml` file to your repo (alongside _config.yml & package.json) with the following content: +8. Add `.travis.yml` file to your repo (alongside \_config.yml & package.json) with the following content: ```yml sudo: false @@ -36,14 +36,14 @@ deploy: 9. Once Travis CI finish the deployment, the generated pages can be found in the `gh-pages` branch of your repository 10. In your GitHub repo's setting, navigate to "GitHub Pages" section and change Source to **gh-pages branch**. -11. Check the webpage at *username*.github.io. +11. Check the webpage at _username_.github.io. ## Project page If you prefer to have a project page on GitHub: -1. Navigate to your repo on GitHub. Go to the **Settings** tab. Change the **Repository name** so your blog is available at <b>username.github.io/*repository*</b>, **repository** can be any name, like *blog* or *hexo*. -2. Edit your **_config.yml**, change the `root:` value to the `/<repository>/` (must starts and ends with a slash, without the brackets). +1. Navigate to your repo on GitHub. Go to the **Settings** tab. Change the **Repository name** so your blog is available at <b>username.github.io/_repository_</b>, **repository** can be any name, like _blog_ or _hexo_. +2. Edit your **\_config.yml**, change the `root:` value to the `/<repository>/` (must starts and ends with a slash, without the brackets). 3. Commit and push. ## Private repository @@ -51,18 +51,18 @@ If you prefer to have a project page on GitHub: The following instruction is adapted from [one-command deployment](/docs/one-command-deployment) page. 1. Install [hexo-deployer-git](https://github.com/hexojs/hexo-deployer-git). -2. Add the following configurations to **_config.yml**, (remove existing lines if any) +2. Add the following configurations to **\_config.yml**, (remove existing lines if any) - ``` yml - deploy: - type: git - repo: https://github.com/<username>/<project> - # example, https://github.com/hexojs/hexojs.github.io - branch: gh-pages - ``` +```yml +deploy: + type: git + repo: https://github.com/<username>/<project> + # example, https://github.com/hexojs/hexojs.github.io + branch: gh-pages +``` 3. Run `hexo clean && hexo deploy`. -4. Check the webpage at *username*.github.io. +4. Check the webpage at _username_.github.io. ## Useful links diff --git a/source/pt-br/docs/gitlab-pages.md b/source/pt-br/docs/gitlab-pages.md index 7b5ce4d6c9..2d4384d923 100644 --- a/source/pt-br/docs/gitlab-pages.md +++ b/source/pt-br/docs/gitlab-pages.md @@ -2,12 +2,12 @@ title: GitLab Pages --- -1. Create a new repository named <b>*username*.gitlab.io</b>, where username is your username on GitLab. If you have already uploaded to other repo, rename the repo instead. +1. Create a new repository named <b>_username_.gitlab.io</b>, where username is your username on GitLab. If you have already uploaded to other repo, rename the repo instead. 2. Enable Shared Runners via `Settings -> CI / CD -> Shared Runners`. 3. Push the files of your Hexo folder to the repository. The `public/` folder is not (and should not be) uploaded by default, make sure the `.gitignore` file contains `public/` line. The folder structure should be roughly similar to [this repo](https://gitlab.com/pages/hexo). -4. Add `.gitlab-ci.yml` file to your repo (alongside _config.yml & package.json) with the following content: +4. Add `.gitlab-ci.yml` file to your repo (alongside \_config.yml & package.json) with the following content: -``` yml +```yml image: node:10-alpine # use nodejs v10 LTS cache: paths: @@ -27,15 +27,15 @@ pages: - master ``` -5. *username*.gitlab.io should be up and running, once GitLab CI finishes the deployment job, +5. _username_.gitlab.io should be up and running, once GitLab CI finishes the deployment job, 6. (Optional) If you wish to inspect the generated site assets (html, css, js, etc), they can be found in the [job artifact](https://docs.gitlab.com/ee/user/project/pipelines/job_artifacts.html). ## Project page If you prefer to have a project page on GitLab: -1. Go to `Settings -> General -> Advanced -> Change path`. Change the value to a name, so the website is available at <b>username.gitlab.io/*name*</b>. It can be any name, like *blog* or *hexo*. -2. Edit **_config.yml**, change the `root:` value from `""` to `"name"`. +1. Go to `Settings -> General -> Advanced -> Change path`. Change the value to a name, so the website is available at <b>username.gitlab.io/_name_</b>. It can be any name, like _blog_ or _hexo_. +2. Edit **\_config.yml**, change the `root:` value from `""` to `"name"`. 3. Commit and push. ## Useful links diff --git a/source/pt-br/docs/helpers.md b/source/pt-br/docs/helpers.md index 9bb3a99cb0..9bfdd14c47 100644 --- a/source/pt-br/docs/helpers.md +++ b/source/pt-br/docs/helpers.md @@ -14,7 +14,7 @@ Você pode usar os helpers padrões do Hexo ou [criar seus próprios helpers per Retorna uma url com o caminho raiz prefixado. Você deve usar esse helper em vez de `config.root + path` desde a versão 2.7 do Hexo. -``` js +```js <%- url_for(path) %> ``` @@ -22,7 +22,7 @@ Retorna uma url com o caminho raiz prefixado. Você deve usar esse helper em vez Retorna a URL relativa de `from` para `to`. -``` js +```js <%- relative_url(from, to) %> ``` @@ -31,13 +31,13 @@ Retorna a URL relativa de `from` para `to`. Insere uma imagem do Gravatar. Se você não especificar o parâmetro [options], as opções padrão serão aplicadas. Caso contrário, você pode configurá-lo para um número que será passado como parâmetro de tamanho para o Gravatar. Finalmente, se você configurá-lo para um objeto, ele será convertido em uma string de consulta de parâmetros para o Gravatar. -``` js +```js <%- gravatar(email, [options]) %> ``` **Exemplos:** -``` js +```js <%- gravatar('a@abc.com') %> // https://www.gravatar.com/avatar/b9b00e66c6b8a70f88c73cb6bdb06787 @@ -54,13 +54,13 @@ Se você não especificar o parâmetro [options], as opções padrão serão apl Carrega arquivos CSS. Onde `path` pode ser um array ou uma string. Se `path` não for prefixado com `/` ou com qualquer protocolo, ele será prefixado com a URL raiz. Se você não adicionar a extensão `.css` após `path`, ela será adicionada automaticamente. Use object type for custom attributes. -``` js +```js <%- css(path, ...) %> ``` **Exemplos:** -``` js +```js <%- css('style.css') %> // <link rel="stylesheet" href="/style.css"> @@ -80,13 +80,13 @@ Carrega arquivos CSS. Onde `path` pode ser um array ou uma string. Se `path` nã Carrega arquivos JavaScript. O `path` pode ser uma array ou uma string. Se `path` não for prefixado com `/` ou com qualquer protocolo, ele será prefixado com a URL raiz. Se você não adicionar a extensão `.js` após `path`, ela será adicionada automaticamente. Use object type for custom attributes. -``` js +```js <%- js(path, ...) %> ``` **Exemplos:** -``` js +```js <%- js('script.js') %> // <script src="/script.js"></script> @@ -106,19 +106,19 @@ Carrega arquivos JavaScript. O `path` pode ser uma array ou uma string. Se `path Insere um link. -``` js +```js <%- link_to(path, [text], [options]) %> ``` -Opção | Descrição | Padrão ---- | --- | --- -`external` | Abre o link em uma nova aba | false -`class` | Nome da classe | -`id` | ID | +| Opção | Descrição | Padrão | +| ---------- | --------------------------- | ------ | +| `external` | Abre o link em uma nova aba | false | +| `class` | Nome da classe | +| `id` | ID | **Exemplos:** -``` js +```js <%- link_to('http://www.google.com') %> // <a href="http://www.google.com" title="http://www.google.com">http://www.google.com</a> @@ -133,22 +133,22 @@ Opção | Descrição | Padrão Insere um link de e-mail. -``` js +```js <%- mail_to(path, [text], [options]) %> ``` -Opção | Descrição ---- | --- -`class` | Nome da classe -`id` | ID -`subject` | Assunto do e-mail -`cc` | CC -`bcc` | BCC -`body` | Conteúdo do e-mail +| Opção | Descrição | +| --------- | ------------------ | +| `class` | Nome da classe | +| `id` | ID | +| `subject` | Assunto do e-mail | +| `cc` | CC | +| `bcc` | BCC | +| `body` | Conteúdo do e-mail | **Exemplos:** -``` js +```js <%- mail_to('a@abc.com') %> // <a href="mailto:a@abc.com" title="a@abc.com">a@abc.com</a> @@ -160,23 +160,23 @@ Opção | Descrição Insere uma imagem. -``` js +```js <%- image_tag(path, [options]) %> ``` -Opção | Descrição ---- | --- -`alt` | Texto alternativo da imagem -`class` | Nome da classe -`id` | ID -`width` | Largura da imagem -`height` | Altura da imagem +| Opção | Descrição | +| -------- | --------------------------- | +| `alt` | Texto alternativo da imagem | +| `class` | Nome da classe | +| `id` | ID | +| `width` | Largura da imagem | +| `height` | Altura da imagem | ### favicon_tag Insere um favicon. -``` js +```js <%- favicon_tag(path) %> ``` @@ -184,18 +184,18 @@ Insere um favicon. Insere um link de feed. -``` js +```js <%- feed_tag(path, [options]) %> ``` -Opção | Descrição | Padrão ---- | --- | --- -`title` | Título do feed | `config.title` -`type` | Tipo do feed | +| Opção | Descrição | Padrão | +| ------- | -------------- | -------------- | +| `title` | Título do feed | `config.title` | +| `type` | Tipo do feed | **Examples:** -``` js +```js <%- feed_tag('atom.xml') %> // <link rel="alternate" href="/atom.xml" title="Hexo" type="application/atom+xml"> @@ -213,7 +213,7 @@ Opção | Descrição | Padrão Verifica se `path` corresponde à URL da página atual. Use opções `strict` para habilitar um modo estrito de correspondência. -``` js +```js <%- is_current(path, [strict]) %> ``` @@ -221,7 +221,7 @@ Verifica se `path` corresponde à URL da página atual. Use opções `strict` pa Verifica se a página atual é a pagina home. -``` js +```js <%- is_home() %> ``` @@ -229,7 +229,7 @@ Verifica se a página atual é a pagina home. Verifica se a página atual é uma postagem. -``` js +```js <%- is_post() %> ``` @@ -237,7 +237,7 @@ Verifica se a página atual é uma postagem. Verifica se a página atual é uma página de arquivo. -``` js +```js <%- is_archive() %> ``` @@ -245,7 +245,7 @@ Verifica se a página atual é uma página de arquivo. Verifica se a página atual é uma página de arquivo anual. -``` js +```js <%- is_year() %> ``` @@ -253,7 +253,7 @@ Verifica se a página atual é uma página de arquivo anual. Verifica se a página atual é uma página de arquivo mensal. -``` js +```js <%- is_month() %> ``` @@ -262,7 +262,7 @@ Verifica se a página atual é uma página de arquivo mensal. Verifica se a página atual é uma página de categoria. Se uma string for dada como parâmetro, também é verificado se a página atual corresponde à categoria dada. -``` js +```js <%- is_category() %> <%- is_category('hobby') %> ``` @@ -272,7 +272,7 @@ Se uma string for dada como parâmetro, também é verificado se a página atual Verifica se a página atual é uma página de tag. Se uma string for dada como parâmetro, também é verificado se a página atual corresponde à tag fornecida. -``` js +```js <%- is_tag() %> <%- is_tag('hobby') %> ``` @@ -283,7 +283,7 @@ Se uma string for dada como parâmetro, também é verificado se a página atual Remove espaços em branco no inicio e fim de uma string. -``` js +```js <%- trim(string) %> ``` @@ -291,13 +291,13 @@ Remove espaços em branco no inicio e fim de uma string. Remove as tags HTML de uma string. -``` js +```js <%- strip_html(string) %> ``` **Exemplo:** -``` js +```js <%- strip_html('It\'s not <b>important</b> anymore!') %> // It's not important anymore! ``` @@ -306,13 +306,13 @@ Remove as tags HTML de uma string. Formata um título com as primeiras letras de palavras importantes em maiúsculo. -``` js +```js <%- titlecase(string) %> ``` **Exemplos:** -``` js +```js <%- titlecase('this is an apple') %> # This is an Apple ``` @@ -321,13 +321,13 @@ Formata um título com as primeiras letras de palavras importantes em maiúsculo Renderiza um conteúdo em Markdown. -``` js +```js <%- markdown(str) %> ``` **Exemplos:** -``` js +```js <%- markdown('make me **strong**') %> // make me <strong>strong</strong> ``` @@ -336,13 +336,13 @@ Renderiza um conteúdo em Markdown. Renderiza uma string. -``` js +```js <%- render(str, engine, [options]) %> ``` **Examples:** -``` js +```js <%- render('p(class="example") Test', 'pug'); %> // <p class="example">Test</p> ``` @@ -353,13 +353,13 @@ See [Rendering](https://hexo.io/pt-br/api/rendering) for more details. Coloca uma quebra de linha no texto a partir de um limite de caracteres, o limite é `length`. Por padrão, o valor de `length` é 80. -``` js +```js <%- word_wrap(str, [length]) %> ``` **Exemplos:** -``` js +```js <%- word_wrap('Once upon a time', 8) %> // Once upon\n a time ``` @@ -368,13 +368,13 @@ Coloca uma quebra de linha no texto a partir de um limite de caracteres, o limit Omite o texto após um certo valor de `length`. O valor padrão de `length` é 30 caracteres. -``` js +```js <%- truncate(text, [options]) %> ``` **Examples:** -``` js +```js <%- truncate('Once upon a time in a world far far away', {length: 17}) %> // Once upon a ti... @@ -389,13 +389,13 @@ Omite o texto após um certo valor de `length`. O valor padrão de `length` é 3 Escapes HTML entities in a string. -``` js +```js <%- escape_html(str) %> ``` **Examples:** -``` js +```js <%- escape_html('<p>Hello "world".</p>') %> // <p>Hello "world".</p> ``` @@ -406,26 +406,26 @@ Escapes HTML entities in a string. Carrega outros arquivos de template. Você pode definir variáveis locais em `locals`. -``` js +```js <%- partial(layout, [locals], [options]) %> ``` -Opção | Descrição | Padrão ---- | --- | --- -`cache` | Conteúdo da cache (usa fragmento de cache) | `false` -`only` | Variáveis locais estritas. Só usa variáveis definidas em `locals` dentro de templates. | `false` +| Opção | Descrição | Padrão | +| ------- | -------------------------------------------------------------------------------------- | ------- | +| `cache` | Conteúdo da cache (usa fragmento de cache) | `false` | +| `only` | Variáveis locais estritas. Só usa variáveis definidas em `locals` dentro de templates. | `false` | ### fragment_cache Cache do conteúdo em um fragmento. Salva o conteúdo dentro de um fragmento e serve o cache quando a próxima requisição chegar. -``` js +```js <%- fragment_cache(id, fn); ``` **Exemplos:** -``` js +```js <%- fragment_cache('header', function(){ return '<header></header>'; }) %> @@ -437,13 +437,13 @@ Cache do conteúdo em um fragmento. Salva o conteúdo dentro de um fragmento e s Insere a data formatada. `date` pode ser data no padrão Unix, string ISO, objeto de data ou objeto [Moment.js]. A Opção `format` usa a definição `date_format` por padrão. -``` js +```js <%- date(date, [format]) %> ``` **Exemplos:** -``` js +```js <%- date(Date.now()) %> // 2013-01-01 @@ -455,13 +455,13 @@ Insere a data formatada. `date` pode ser data no padrão Unix, string ISO, objet Insere a data no formato XML. `date` pode ser data no padrão Unix, string ISO, objeto de data ou objeto [Moment.js]. -``` js +```js <%- date_xml(date) %> ``` **Exemplos:** -``` js +```js <%- date_xml(Date.now()) %> // 2013-01-01T00:00:00.000Z ``` @@ -470,13 +470,13 @@ Insere a data no formato XML. `date` pode ser data no padrão Unix, string ISO, Insere a hora formatada. `date` pode ser data no padrão Unix, string ISO, objeto de data ou objeto [Moment.js]. A Opção `format` usa a definição `time_format` por padrão. -``` js +```js <%- time(date, [format]) %> ``` **Exemplo:** -``` js +```js <%- time(Date.now()) %> // 13:05:12 @@ -488,13 +488,13 @@ Insere a hora formatada. `date` pode ser data no padrão Unix, string ISO, objet Insere a data e a hora formatadas. `date` pode ser data no padrão Unix, string ISO, objeto de data ou objeto [Moment.js]. A Opção `format` usa a definição `date_format + time_format` por padrão. -``` js +```js <%- full_date(date, [format]) %> ``` **Exemplos:** -``` js +```js <%- full_date(new Date()) %> // Jan 1, 2013 0:00:00 @@ -512,51 +512,51 @@ Biblioteca [Moment.js]. Insere uma lista de todas as categorias. -``` js +```js <%- list_categories([options]) %> ``` -Opção | Descrição | Padrão ---- | --- | --- -`orderby` | Critério de ordenação das categorias | name -`order` | Tipo de ordenação. `1`, `asc` para ascendente; `-1`, `desc` para descendente | 1 -`show_count` | Exibir o número de postagens para cada categoria | true -`style` | Estilo para exibir a lista de categorias. `list` exibe as categorias em uma lista não ordenada. | list -`separator` | Separador entre categorias. (Só funciona se `style` não for `list`). | , -`depth` | Níveis de categorias a serem exibidos. `0` exibe todas as categorias e suas categorias filhas; `-1` é semelhante a `0`, mas exibe as categorias e suas filhas em um mesmo nível hierárquico; `1` exibe apenas as categorias de nível superior. | 0 -`class` | Nome da classe da lista de categorias. | category -`transform` | A função que altera a exibição do nome da categoria. | -`suffix`| Adiciona um sufixo para o link. | None +| Opção | Descrição | Padrão | +| ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | +| `orderby` | Critério de ordenação das categorias | name | +| `order` | Tipo de ordenação. `1`, `asc` para ascendente; `-1`, `desc` para descendente | 1 | +| `show_count` | Exibir o número de postagens para cada categoria | true | +| `style` | Estilo para exibir a lista de categorias. `list` exibe as categorias em uma lista não ordenada. | list | +| `separator` | Separador entre categorias. (Só funciona se `style` não for `list`). | , | +| `depth` | Níveis de categorias a serem exibidos. `0` exibe todas as categorias e suas categorias filhas; `-1` é semelhante a `0`, mas exibe as categorias e suas filhas em um mesmo nível hierárquico; `1` exibe apenas as categorias de nível superior. | 0 | +| `class` | Nome da classe da lista de categorias. | category | +| `transform` | A função que altera a exibição do nome da categoria. | +| `suffix` | Adiciona um sufixo para o link. | None | ### list_tags Insere uma lista de tags. -``` js +```js <%- list_tags([options]) %> ``` -Opção | Descrição | Padrão ---- | --- | --- -`orderby` | Critério de ordenação das tags | name -`order` | Tipo de ordem. `1`, `asc` para ascendente; `-1`, `desc` para descendente | 1 -`show_count` | Exibir o número de postagens para cada tag | true -`style` | Estilo para exibir a lista de tags. `list` exibe as tags em uma lista não ordenada. | list -`separator`| Separador entre tags. (Só funciona se `style` não for `list`). | , -`class` | Class name of tag list (string) or customize each tag's class (object, see below). | tag -`transform` | A função que altera a exibição do nome da tag. | -`amount` | O número de tags a exibir (0 = ilimitado) | 0 -`suffix` | Adiciona um sufixo para o link. | Nenhum +| Opção | Descrição | Padrão | +| ------------ | ----------------------------------------------------------------------------------- | ------ | +| `orderby` | Critério de ordenação das tags | name | +| `order` | Tipo de ordem. `1`, `asc` para ascendente; `-1`, `desc` para descendente | 1 | +| `show_count` | Exibir o número de postagens para cada tag | true | +| `style` | Estilo para exibir a lista de tags. `list` exibe as tags em uma lista não ordenada. | list | +| `separator` | Separador entre tags. (Só funciona se `style` não for `list`). | , | +| `class` | Class name of tag list (string) or customize each tag's class (object, see below). | tag | +| `transform` | A função que altera a exibição do nome da tag. | +| `amount` | O número de tags a exibir (0 = ilimitado) | 0 | +| `suffix` | Adiciona um sufixo para o link. | Nenhum | Class advanced customization: -Option | Description | Default ---- | --- | --- -`class.ul` | `<ul>` class name (only for style `list`) | `tag-list` (list style) -`class.li` | `<li>` class name (only for style `list`) | `tag-list-item` (list style) -`class.a` | `<a>` class name | `tag-list-link` (list style) `tag-link` (normal style) -`class.label` | `<span>` class name where the tag label is stored (only for normal style, when `class.label` is set the label is put in a `<span>`) | `tag-label` (normal style) -`class.count` | `<span>` class name where the tag counter is stored (only when `show_count` is `true`) | `tag-list-count` (list style) `tag-count` (normal style) +| Option | Description | Default | +| ------------- | ----------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------- | +| `class.ul` | `<ul>` class name (only for style `list`) | `tag-list` (list style) | +| `class.li` | `<li>` class name (only for style `list`) | `tag-list-item` (list style) | +| `class.a` | `<a>` class name | `tag-list-link` (list style) `tag-link` (normal style) | +| `class.label` | `<span>` class name where the tag label is stored (only for normal style, when `class.label` is set the label is put in a `<span>`) | `tag-label` (normal style) | +| `class.count` | `<span>` class name where the tag counter is stored (only when `show_count` is `true`) | `tag-list-count` (list style) `tag-count` (normal style) | Examples: @@ -571,60 +571,60 @@ Examples: Insere uma lista de arquivos (archives). -``` js +```js <%- list_archives([options]) %> ``` -Opção | Descrição | Padrão ---- | --- | --- -`type` | Tipo. Esse valor pode ser `yearly` ou `monthly`. | monthly -`order` | Tipo de ordem. `1`, `asc` para ascendente; `-1`, `desc` para descendente | 1 -`show_count` | Exibir o número de postagens para cada arquivo | true -`format` | Formato da data | MMMM YYYY -`style` | Estilo para exibir a lista de arquivos. `list` exibe arquivos em uma lista não ordenada. | list -`separator`| Separador entre arquivos. (Só funciona se `style` não for `list`) | , -`class` | Nome da classe da lista de arquivos. | archive -`transform` | A função que altera a exibição do nome do archive. | +| Opção | Descrição | Padrão | +| ------------ | ---------------------------------------------------------------------------------------- | --------- | +| `type` | Tipo. Esse valor pode ser `yearly` ou `monthly`. | monthly | +| `order` | Tipo de ordem. `1`, `asc` para ascendente; `-1`, `desc` para descendente | 1 | +| `show_count` | Exibir o número de postagens para cada arquivo | true | +| `format` | Formato da data | MMMM YYYY | +| `style` | Estilo para exibir a lista de arquivos. `list` exibe arquivos em uma lista não ordenada. | list | +| `separator` | Separador entre arquivos. (Só funciona se `style` não for `list`) | , | +| `class` | Nome da classe da lista de arquivos. | archive | +| `transform` | A função que altera a exibição do nome do archive. | ### list_posts Insere uma lista de posts. -``` js +```js <%- list_posts([options]) %> ``` -Opção | Descrição | Padrão ---- | --- | --- -`orderby` | Critério de ordenação de postagens | date -`order` | Tipo de ordem. `1`, `asc` para ascendente; `-1`, `desc` para descendente | 1 -`style` | Estilo para exibir a lista de postagens. `list` exibe as postagens em uma lista não ordenada. | list -`separator` | Separador entre postagens. (Só funciona se `style` não for `list`) | , -`class` | Nome da classe da lista de postagem. | post -`amount` | O número de postagens a serem exibidas (0 = ilimitado) | 6 -`transform` | A função que altera a exibição do nome do post. | +| Opção | Descrição | Padrão | +| ----------- | --------------------------------------------------------------------------------------------- | ------ | +| `orderby` | Critério de ordenação de postagens | date | +| `order` | Tipo de ordem. `1`, `asc` para ascendente; `-1`, `desc` para descendente | 1 | +| `style` | Estilo para exibir a lista de postagens. `list` exibe as postagens em uma lista não ordenada. | list | +| `separator` | Separador entre postagens. (Só funciona se `style` não for `list`) | , | +| `class` | Nome da classe da lista de postagem. | post | +| `amount` | O número de postagens a serem exibidas (0 = ilimitado) | 6 | +| `transform` | A função que altera a exibição do nome do post. | ### tagcloud Insere uma nuvem de tags. -``` js +```js <%- tagcloud([tags], [options]) %> ``` -Opção | Descrição | Padrão ---- | --- | --- -`min_font` | Tamanho mínimo da fonte | 10 -`max_font` | Tamanho máximo da fonte | 20 -`unit` | Unidade de tamanho de fonte | px -`amount` | Quantidade total de tags | 40 -`orderby` | Critério de ordenação de tags | name -`order` | Tipo de ordem. `1`, `asc` para ascendente; `-1`, `desc` para descendente | 1 -`color` | Colorizar a nuvem de tags? | false -`start_color` | Cor inicial. Você pode usar o padrão hexadecimal (`#b700ff`), rgba (`rgba(183, 0, 255, 1)`), hsla (`hsla(283, 100%, 50%, 1)`) ou [color keywords]. Esta opção só funciona quando `color` é `true`. | -`end_color` | Cor final. Você pode usar o padrão hexadecimal (`#b700ff`), rgba (`rgba(183, 0, 255, 1)`), hsla (`hsla(283, 100%, 50%, 1)`) ou [color keywords]. Esta opção só funciona quando `color` é `true`. | -`class` | Class name prefix of tags -`level` | The number of different class names. This option only works when `class` is set. | 10 +| Opção | Descrição | Padrão | +| ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------ | +| `min_font` | Tamanho mínimo da fonte | 10 | +| `max_font` | Tamanho máximo da fonte | 20 | +| `unit` | Unidade de tamanho de fonte | px | +| `amount` | Quantidade total de tags | 40 | +| `orderby` | Critério de ordenação de tags | name | +| `order` | Tipo de ordem. `1`, `asc` para ascendente; `-1`, `desc` para descendente | 1 | +| `color` | Colorizar a nuvem de tags? | false | +| `start_color` | Cor inicial. Você pode usar o padrão hexadecimal (`#b700ff`), rgba (`rgba(183, 0, 255, 1)`), hsla (`hsla(283, 100%, 50%, 1)`) ou [color keywords]. Esta opção só funciona quando `color` é `true`. | +| `end_color` | Cor final. Você pode usar o padrão hexadecimal (`#b700ff`), rgba (`rgba(183, 0, 255, 1)`), hsla (`hsla(283, 100%, 50%, 1)`) ou [color keywords]. Esta opção só funciona quando `color` é `true`. | +| `class` | Class name prefix of tags | +| `level` | The number of different class names. This option only works when `class` is set. | 10 | ## Miscelânea @@ -632,35 +632,35 @@ Opção | Descrição | Padrão Insere um paginador. -``` js +```js <%- paginator(options) %> ``` -Opção | Descrição | Padrão ---- | --- | --- -`base` | URL base | / -`format` | Formato da URL | page/%d/ -`total` | Número de páginas | 1 -`current` | Número da página atual | 0 -`prev_text` | O texto do link da página anterior. Funciona apenas se `prev_next` estiver definido como `true`. | Prev -`next_text` | O texto do link da próxima página. Funciona apenas se `prev_next` estiver definido como `true`. | Next -`space` | Espaço do texto | &hellp; -`prev_next` | Exibir os links anteriores e seguintes | true -`end_size` | O número de páginas exibidas no início e no final | 1 -`mid_size` | O número de páginas exibidas entre a página atual, mas não incluindo a página atual | 2 -`show_all` | Exibir todas as páginas. Se isso for definido como `true`, `end_size` e `mid_size` não irão funcionar. | false -`escape` | Escape HTML tags | true +| Opção | Descrição | Padrão | +| ----------- | ------------------------------------------------------------------------------------------------------ | -------- | +| `base` | URL base | / | +| `format` | Formato da URL | page/%d/ | +| `total` | Número de páginas | 1 | +| `current` | Número da página atual | 0 | +| `prev_text` | O texto do link da página anterior. Funciona apenas se `prev_next` estiver definido como `true`. | Prev | +| `next_text` | O texto do link da próxima página. Funciona apenas se `prev_next` estiver definido como `true`. | Next | +| `space` | Espaço do texto | &hellp; | +| `prev_next` | Exibir os links anteriores e seguintes | true | +| `end_size` | O número de páginas exibidas no início e no final | 1 | +| `mid_size` | O número de páginas exibidas entre a página atual, mas não incluindo a página atual | 2 | +| `show_all` | Exibir todas as páginas. Se isso for definido como `true`, `end_size` e `mid_size` não irão funcionar. | false | +| `escape` | Escape HTML tags | true | **Examples:** -``` js +```js <%- paginator({ prev_text: '<', next_text: '>' }) %> ``` -``` html +```html <!-- Rendered as --> <a href="/1/"><</a> <a href="/1/">1</a> @@ -669,7 +669,7 @@ Opção | Descrição | Padrão <a href="/3/">></a> ``` -``` js +```js <%- paginator({ prev_text: '<i class="fa fa-angle-left"></i>', next_text: '<i class="fa fa-angle-right"></i>', @@ -677,7 +677,7 @@ Opção | Descrição | Padrão }) %> ``` -``` html +```html <!-- Rendered as --> <a href="/1/"><i class="fa fa-angle-left"></i></a> <a href="/1/">1</a> @@ -690,33 +690,33 @@ Opção | Descrição | Padrão Insere o formulário de busca do Google. -``` js +```js <%- search_form(options) %> ``` -Opção | Descrição | Padrão ---- | --- | --- -`class` | O nome da classe do formulário | search-form -`text`| Palavra de sugestão de busca | Search -`button`| Exibir o botão de busca. O valor pode ser um booleano ou uma string. Quando o valor é uma string, ele será o texto do botão. | false +| Opção | Descrição | Padrão | +| -------- | ---------------------------------------------------------------------------------------------------------------------------- | ----------- | +| `class` | O nome da classe do formulário | search-form | +| `text` | Palavra de sugestão de busca | Search | +| `button` | Exibir o botão de busca. O valor pode ser um booleano ou uma string. Quando o valor é uma string, ele será o texto do botão. | false | ### number_format Formata um número. -``` js +```js <%- number_format(number, [options]) %> ``` -Opção | Descrição | Padrão ---- | --- | --- -`precision` | A precisão do número. O valor pode ser `false` ou um número inteiro não negativo. | false -`delimiter` | O delimitador de casa de milhares | , -`separator` | O separador entre os dígitos fracionários e inteiros. | . +| Opção | Descrição | Padrão | +| ----------- | --------------------------------------------------------------------------------- | ------ | +| `precision` | A precisão do número. O valor pode ser `false` ou um número inteiro não negativo. | false | +| `delimiter` | O delimitador de casa de milhares | , | +| `separator` | O separador entre os dígitos fracionários e inteiros. | . | **Exemplos:** -``` js +```js <%- number_format(12345.67, {precision: 1}) %> // 12,345.68 @@ -737,13 +737,13 @@ Opção | Descrição | Padrão Inserts [generator tag](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta). -``` js +```js <%- meta_generator() %> ``` **Examples:** -``` js +```js <%- meta_generator() %> // <meta name="generator" content="Hexo 4.0.0"> ``` @@ -752,47 +752,47 @@ Inserts [generator tag](https://developer.mozilla.org/en-US/docs/Web/HTML/Elemen Insere dados do [Open Graph]. -``` js +```js <%- open_graph([options]) %> ``` -Opção | Descrição | Padrão ---- | --- | --- -`title` | Título da página (`og:title`) | `page.title` -`type` | Tipo de página (`og:type`) | article(post page)<br>website(non-post page) -`url` | URL da página (`og:url`) | `url` -`image` | Capa da página (`og:image`) | All images in the content -`author` | Article author (`og:article:author`) | `config.author` -`date` | Article published time (`og:article:published_time`) | Page published time -`updated` | Article modified time (`og:article:modified_time`) | Page modified time -`language` | Article language (`og:locale`) | `page.lang \|\| page.language \|\| config.language` -`site_name` | Nome do site (`og:site_name`) | `config.title` -`description`| Descrição da página (`og:description`) | Trecho da página ou os 200 primeiros caracteres do conteúdo -`twitter_card` | Tipo de Twitter card (`twitter:card`) | summary -`twitter_id` | Twitter ID (`twitter:creator`) | -`twitter_site` | Site do Twitter (`twitter:site`) | -`google_plus` | Link de perfil do Google+ | -`fb_admins` | ID de administrador do Facebook | -`fb_app_id` | ID da aplicação do Facebook | +| Opção | Descrição | Padrão | +| -------------- | ---------------------------------------------------- | ----------------------------------------------------------- | +| `title` | Título da página (`og:title`) | `page.title` | +| `type` | Tipo de página (`og:type`) | article(post page)<br>website(non-post page) | +| `url` | URL da página (`og:url`) | `url` | +| `image` | Capa da página (`og:image`) | All images in the content | +| `author` | Article author (`og:article:author`) | `config.author` | +| `date` | Article published time (`og:article:published_time`) | Page published time | +| `updated` | Article modified time (`og:article:modified_time`) | Page modified time | +| `language` | Article language (`og:locale`) | `page.lang \|\| page.language \|\| config.language` | +| `site_name` | Nome do site (`og:site_name`) | `config.title` | +| `description` | Descrição da página (`og:description`) | Trecho da página ou os 200 primeiros caracteres do conteúdo | +| `twitter_card` | Tipo de Twitter card (`twitter:card`) | summary | +| `twitter_id` | Twitter ID (`twitter:creator`) | +| `twitter_site` | Site do Twitter (`twitter:site`) | +| `google_plus` | Link de perfil do Google+ | +| `fb_admins` | ID de administrador do Facebook | +| `fb_app_id` | ID da aplicação do Facebook | ### toc Analisa todas as tags de título (h1~h6) no conteúdo e insere um índice. -``` js +```js <%- toc(str, [options]) %> ``` -Opção | Descrição | Padrão ---- | --- | --- -`class` | Nome da classe | toc -`list_number` | Exibe o número da lista | true -`max_depth` | Profundidade máxima do cabeçalho gerado | 6 -`min_depth` | Minimum heading depth of generated toc | 1 +| Opção | Descrição | Padrão | +| ------------- | --------------------------------------- | ------ | +| `class` | Nome da classe | toc | +| `list_number` | Exibe o número da lista | true | +| `max_depth` | Profundidade máxima do cabeçalho gerado | 6 | +| `min_depth` | Minimum heading depth of generated toc | 1 | **Exemplos:** -``` js +```js <%- toc(page.content) %> ``` @@ -808,7 +808,7 @@ Please see below PRs. - https://github.com/hexojs/hexo/pull/4871 - https://github.com/hexojs/hexo-util/pull/269 - https://github.com/hexojs/hexo-renderer-markdown-it/pull/174 -{% endnote %} + {% endnote %} [color keywords]: http://www.w3.org/TR/css3-color/#svg-color [Moment.js]: http://momentjs.com/ diff --git a/source/pt-br/docs/index.md b/source/pt-br/docs/index.md index 6b9d9f75da..da544c2f6c 100644 --- a/source/pt-br/docs/index.md +++ b/source/pt-br/docs/index.md @@ -2,7 +2,7 @@ title: Documentação --- -Bem-vindo à documentação do Hexo. Se você encontrar algum problema ao usar o Hexo, dê uma olhada no [guia de solução de problemas](troubleshooting.html), abra uma issue no [GitHub](https://github.com/hexojs/hexo/issues) ou inicie um tópico no [Google Group](https://groups.google.com/group/hexo). +Bem-vindo à documentação do Hexo. Se você encontrar algum problema ao usar o Hexo, dê uma olhada no [guia de solução de problemas](troubleshooting.html), abra uma issue no [GitHub](https://github.com/hexojs/hexo/issues) ou inicie um tópico no [Google Group](https://groups.google.com/group/hexo). ## O que é o Hexo? @@ -23,7 +23,7 @@ Instalar o Hexo é bastante fácil. No entanto, você precisa ter algumas outras Se o seu computador já possui estes, parabéns! Basta instalar o Hexo com o npm: -``` bash +```bash $ npm install -g hexo-cli ``` @@ -69,7 +69,7 @@ If you installed Node.js using Snap, you may need to manually run `npm install` Uma vez que todos os requisitos estão instalados, você pode instalar o Hexo com npm: -``` bash +```bash $ npm install -g hexo-cli ``` @@ -81,15 +81,15 @@ Please note we do not provide bugfixes to past versions of Hexo. We highly recommend to always install the [latest version](https://www.npmjs.com/package/hexo?activeTab=versions) of Hexo and the [recommended version](#Requirements) of Node.js, whenever possible. -Hexo version | Minimum (Node.js version) | Less than (Node.js version) ---- | --- | --- -7.0+ | 14.0.0 | latest -6.2+ | 12.13.0 | latest -6.0+ | 12.13.0 | 18.5.0 -5.0+ | 10.13.0 | 12.0.0 -4.1 - 4.2 | 8.10 | 10.0.0 -4.0 | 8.6 | 8.10.0 -3.3 - 3.9 | 6.9 | 8.0.0 -3.2 - 3.3 | 0.12 | unknown -3.0 - 3.1 | 0.10 or iojs | unknown -0.0.1 - 2.8 | 0.10 | unknown \ No newline at end of file +| Hexo version | Minimum (Node.js version) | Less than (Node.js version) | +| ------------ | ------------------------- | --------------------------- | +| 7.0+ | 14.0.0 | latest | +| 6.2+ | 12.13.0 | latest | +| 6.0+ | 12.13.0 | 18.5.0 | +| 5.0+ | 10.13.0 | 12.0.0 | +| 4.1 - 4.2 | 8.10 | 10.0.0 | +| 4.0 | 8.6 | 8.10.0 | +| 3.3 - 3.9 | 6.9 | 8.0.0 | +| 3.2 - 3.3 | 0.12 | unknown | +| 3.0 - 3.1 | 0.10 or iojs | unknown | +| 0.0.1 - 2.8 | 0.10 | unknown | diff --git a/source/pt-br/docs/internationalization.md b/source/pt-br/docs/internationalization.md index 8f5721b7a8..5c43cd392a 100644 --- a/source/pt-br/docs/internationalization.md +++ b/source/pt-br/docs/internationalization.md @@ -1,9 +1,10 @@ --- title: Internacionalização (i18n) --- + Você pode usar a internacionalização para apresentar seu site em diferentes idiomas. O idioma padrão é definido modificando a configuração `language` em `_config.yml`. Você também pode definir vários idiomas e modificar a ordem dos idiomas padrão. -``` yaml +```yaml language: zh-tw language: @@ -19,7 +20,7 @@ Os arquivos de idioma podem ser arquivos YAML ou JSON. Você deve inseri-los no Use os helpers `__` ou `_p` nos templates para traduzir as strings. O primeiro é para uso normal e o segundo é para strings no plural. Por exemplo: -``` yaml en.yml +```yaml en.yml index: title: Home add: Add @@ -29,7 +30,7 @@ index: other: %d videos ``` -``` js +```js <%= __('index.title') %> // Home @@ -41,13 +42,13 @@ index: Você pode definir o idioma das páginas no front-matter ou modificar a configuração `i18n_dir` no arquivo `_config.yml` para habilitar a detecção automática pelo Hexo. -``` yaml +```yaml i18n_dir: :lang ``` O valor padrão da configuração `i18n_dir` é `:lang`, o que significa que o Hexo detectará o idioma dentro do primeiro segmento de URL. Por exemplo: -``` plain +```plain /index.html => en /archives/index.html => en /zh-tw/index.html => zh-tw diff --git a/source/pt-br/docs/migration.md b/source/pt-br/docs/migration.md index 732f1d5bfd..0b3f2f1a13 100644 --- a/source/pt-br/docs/migration.md +++ b/source/pt-br/docs/migration.md @@ -1,17 +1,18 @@ --- title: Migração --- + ## RSS Primeiramente, instale o plugin `hexo-migrator-rss`. -``` bash +```bash $ npm install hexo-migrator-rss --save ``` Uma vez que o plugin esteja instalado, execute o seguinte comando para migrar todas as postagens do RSS. A opção `source` pode ser um caminho de arquivo ou uma URL. -``` bash +```bash $ hexo migrate rss <source> ``` @@ -21,7 +22,7 @@ Mova todos os arquivos no diretório `_posts` do Jekyll para o diretório `sourc Modifique a configuração `new_post_name` no arquivo `_config.yml`: -``` yaml +```yaml new_post_name: :year-:month-:day-:title.md ``` @@ -31,7 +32,7 @@ Mova todos os arquivos do diretório `source/_posts` do Octopress para o diretó Modifique a configuração `new_post_name` no arquivo `_config.yml`: -``` yaml +```yaml new_post_name: :year-:month-:day-:title.md ``` @@ -39,7 +40,7 @@ new_post_name: :year-:month-:day-:title.md Primeiro, instale o plugin `hexo-migrator-wordpress`. -``` bash +```bash $ npm install hexo-migrator-wordpress --save ``` @@ -47,7 +48,7 @@ Exporte o seu site WordPress indo para "Tools" → "Export" → "WordPress" (ou Agora execute: -``` bash +```bash $ hexo migrate wordpress <source> ``` diff --git a/source/pt-br/docs/one-command-deployment.md b/source/pt-br/docs/one-command-deployment.md index bb4f959559..c352a28ea5 100644 --- a/source/pt-br/docs/one-command-deployment.md +++ b/source/pt-br/docs/one-command-deployment.md @@ -1,27 +1,28 @@ --- title: Implantação --- + O Hexo fornece uma estratégia de implantação (deployment) rápida e fácil. Você só precisa de um único comando para implantar seu site no servidor. -``` bash +```bash $ hexo deploy ``` Antes da sua primeira implantação, você terá que modificar algumas configurações em `_config.yml`. Uma configuração de implantação válida deve ter um campo `type`. Por exemplo: -``` yaml +```yaml deploy: type: git ``` Você pode implantar o site em mais de um servidor. O Hexo executará cada implantação na ordem da declaração. -``` yaml +```yaml deploy: -- type: git - repo: -- type: heroku - repo: + - type: git + repo: + - type: heroku + repo: ``` Refer to the [Plugins](https://hexo.io/plugins/) list for more deployment plugins. @@ -44,17 +45,17 @@ deploy: message: [message] ``` -Option | Description | Default ---- | --- | --- -`repo` | URL of the target repository | -`branch` | Branch name. | `gh-pages` (GitHub)<br>`coding-pages` (Coding.net)<br>`master` (others) -`message` | Customize commit message. | `Site updated: {% raw %}{{ now('YYYY-MM-DD HH:mm:ss') }}{% endraw %}` -`token` | Optional token value to authenticate with the repo. Prefix with `$` to read token from environment variable +| Option | Description | Default | +| --------- | ----------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- | +| `repo` | URL of the target repository | +| `branch` | Branch name. | `gh-pages` (GitHub)<br>`coding-pages` (Coding.net)<br>`master` (others) | +| `message` | Customize commit message. | `Site updated: {% raw %}{{ now('YYYY-MM-DD HH:mm:ss') }}{% endraw %}` | +| `token` | Optional token value to authenticate with the repo. Prefix with `$` to read token from environment variable | 3. Deploy your site `hexo clean && hexo deploy`. - - You will be prompted with username and password of the target repository, unless you authenticate with a token or ssh key. - - hexo-deployer-git does not store your username and password. Use [git-credential-cache](https://git-scm.com/docs/git-credential-cache) to store them temporarily. +- You will be prompted with username and password of the target repository, unless you authenticate with a token or ssh key. +- hexo-deployer-git does not store your username and password. Use [git-credential-cache](https://git-scm.com/docs/git-credential-cache) to store them temporarily. 4. Navigate to your repository settings and change the "Pages" branch to `gh-pages` (or the branch specified in your config). The deployed site should be live on the link shown on the "Pages" setting. @@ -62,35 +63,35 @@ Option | Description | Default Instale o pacote [hexo-deployer-heroku]. -``` bash +```bash $ npm install hexo-deployer-heroku --save ``` Editando as configurações. -``` yaml +```yaml deploy: type: heroku repo: <repository url> message: [message] ``` -Opção | Descrição ---- | --- -`repo`, `repository` | URL do repositório no Heroku -`message` | Customiza a mensagem de commit (O padão é: `Site updated: {% raw %}{{ now('YYYY-MM-DD HH:mm:ss') }}{% endraw %}`) +| Opção | Descrição | +| -------------------- | ----------------------------------------------------------------------------------------------------------------- | +| `repo`, `repository` | URL do repositório no Heroku | +| `message` | Customiza a mensagem de commit (O padão é: `Site updated: {% raw %}{{ now('YYYY-MM-DD HH:mm:ss') }}{% endraw %}`) | ## Rsync Instale o pacote [hexo-deployer-rsync]. -``` bash +```bash $ npm install hexo-deployer-rsync --save ``` Editando as configurações. -``` yaml +```yaml deploy: type: rsync host: <host> @@ -102,49 +103,49 @@ deploy: ignore_errors: [true|false] ``` -Opção | Descrição | Padão ---- | --- | --- -`host` | Endereço do host remoto | -`user` | Nome de usuário | -`root` | Diretório raiz do host remoto | -`port` | Porta | 22 -`delete` | Exclui arquivos antigos no host remoto | true -`verbose` | Exibi mensagens detalhadas | true -`ignore_errors` | Ignora erros | false +| Opção | Descrição | Padão | +| --------------- | -------------------------------------- | ----- | +| `host` | Endereço do host remoto | +| `user` | Nome de usuário | +| `root` | Diretório raiz do host remoto | +| `port` | Porta | 22 | +| `delete` | Exclui arquivos antigos no host remoto | true | +| `verbose` | Exibi mensagens detalhadas | true | +| `ignore_errors` | Ignora erros | false | ## OpenShift Instale o pacote [hexo-deployer-openshift]. -``` bash +```bash $ npm install hexo-deployer-openshift --save ``` Editando as configurações. -``` yaml +```yaml deploy: type: openshift repo: <repository url> message: [message] ``` -Opção | Descrição ---- | --- -`repo` | URL do repositório no OpenShift -`message` | Customiza a mensagem de commit (O padrão é `Site updated: {% raw %}{{ now('YYYY-MM-DD HH:mm:ss') }}{% endraw %}`) +| Opção | Descrição | +| --------- | ----------------------------------------------------------------------------------------------------------------- | +| `repo` | URL do repositório no OpenShift | +| `message` | Customiza a mensagem de commit (O padrão é `Site updated: {% raw %}{{ now('YYYY-MM-DD HH:mm:ss') }}{% endraw %}`) | ## FTPSync Instale o pacote [hexo-deployer-ftpsync]. -``` bash +```bash $ npm install hexo-deployer-ftpsync --save ``` Editando as configurações. -``` yaml +```yaml deploy: type: ftpsync host: <host> @@ -156,27 +157,29 @@ deploy: verbose: [true|false] ``` -Opção | Descrição | Padrão ---- | --- | --- -`host` | Endereço do host remoto | -`user` | Nome de usuário | -`pass` | Senha | -`remote` | Diretório raiz do host remoto | `/` -`port` | Porta | 21 -`clear` | Remove all files and directories from the remote directory before upload | false -`verbose` | Exibi mensagens detalhadas | false +| Opção | Descrição | Padrão | +| ------------- | ------------------------------------------------------------------------ | ------ | +| `host` | Endereço do host remoto | +| `user` | Nome de usuário | +| `pass` | Senha | +| `remote` | Diretório raiz do host remoto | `/` | +| `port` | Porta | 21 | +| `clear` | Remove all files and directories from the remote directory before upload | false | +| `ignore` | Ignora os arquivos no host remoto | +| `connections` | Número de conexões | 1 | +| `verbose` | Exibi mensagens detalhadas | false | ## SFTP Instale o pacote [hexo-deployer-sftp]. Implantação do site via SFTP, permitindo conexões sem senhas usando "ssh-agent". -``` bash +```bash $ npm install hexo-deployer-sftp --save ``` Editando as configurações. -``` yaml +```yaml deploy: type: sftp host: <host> @@ -189,16 +192,16 @@ deploy: agent: [path/to/agent/socket] ``` -Opção | Descrição | Padrão ---- | --- | --- -`host` | Endereço do host remoto | -`user` | Nome de usuário | -`pass` | Senha | -`remotePath` | Diretório raiz do host remoto | `/` -`port` | Porta | 22 -`privateKey` | Caminho para uma chave ssh privada | -`passphrase` | Frase secreta opcional para a chave privada | -`agent` | Caminho para o socket do agente ssh | `$SSH_AUTH_SOCK` +| Opção | Descrição | Padrão | +| ------------ | ------------------------------------------- | ---------------- | +| `host` | Endereço do host remoto | +| `user` | Nome de usuário | +| `pass` | Senha | +| `remotePath` | Diretório raiz do host remoto | `/` | +| `port` | Porta | 22 | +| `privateKey` | Caminho para uma chave ssh privada | +| `passphrase` | Frase secreta opcional para a chave privada | +| `agent` | Caminho para o socket do agente ssh | `$SSH_AUTH_SOCK` | ## Vercel @@ -256,8 +259,8 @@ After a few moments, your website will be deployed. 2. Modifique a configuração. - ``` yaml - deploy: +```yaml +deploy: - type: rss3 endpoint: https://hub.rss3.io privateKey: 47e18d6c386898b424025cd9db446f779ef24ad33a26c499c87bb3d9372540ba @@ -267,15 +270,15 @@ After a few moments, your website will be deployed. api: key: d693df715d3631e489d6 secret: ee8b74626f12b61c1a4bde3b8c331ad390567c86ba779c9b18561ee92c1cbff0 - ``` - -| Parâmetros | Descrição | -| ----------------- | ---------------------- | -| `endpoint` | Um link para o hub RSS3 | -| `privateKey` | Sua chave privada, 64 bytes | -| `ipfs/deploy` | Se deve implantar no IPFS | -| `ipfs/gateway` | Gateway de API IPFS | -| `ipfs/api/key` | Conteúdo de verificação relacionado ao gateway IPFS | +``` + +| Parâmetros | Descrição | +| ----------------- | --------------------------------------------------- | +| `endpoint` | Um link para o hub RSS3 | +| `privateKey` | Sua chave privada, 64 bytes | +| `ipfs/deploy` | Se deve implantar no IPFS | +| `ipfs/gateway` | Gateway de API IPFS | +| `ipfs/api/key` | Conteúdo de verificação relacionado ao gateway IPFS | | `ipfs/api/secret` | Conteúdo de verificação relacionado ao gateway IPFS | 3. Gere arquivos estáticos diff --git a/source/pt-br/docs/permalinks.md b/source/pt-br/docs/permalinks.md index c1ba10099e..e0102f3693 100644 --- a/source/pt-br/docs/permalinks.md +++ b/source/pt-br/docs/permalinks.md @@ -8,78 +8,78 @@ Você pode especificar os links permanentes (permalinks) para o seu site em `_co Besides the following variables, you can use any attributes in the permalink except `:path` and `:permalink`. -Variável | Descrição ---- | --- -`:year` | Ano da publicação da postagem (4 dígitos) -`:month` | Mês da publicação da postagem (2 dígitos) -`:i_month` | Mês da publicação da postagem (sem zero à esquerda) -`:day` | Dia da publicação da postagem (2 dígitos) -`:i_day` | Dia da publicação da postagem (sem zero à esquerda) -`:hour` | Published hour of posts (2-digit) -`:minute` | Published minute of posts (2-digit) -`:second` | Published second of posts (2-digit) -`:title` | Filename (relative to "source/_posts/" folder) -`:name` | Filename -`:post_title` | Título da postagem -`:id` | ID da postagem (_not persistent across [cache reset](/pt-br/docs/commands#clean)_) -`:category` | Categorias. Se a postagem não possuir uma categoria, será usado o valor de `default_category`. -`:hash` | SHA1 hash of filename (same as `:title`) and date (12-hexadecimal) +| Variável | Descrição | +| ------------- | ---------------------------------------------------------------------------------------------- | +| `:year` | Ano da publicação da postagem (4 dígitos) | +| `:month` | Mês da publicação da postagem (2 dígitos) | +| `:i_month` | Mês da publicação da postagem (sem zero à esquerda) | +| `:day` | Dia da publicação da postagem (2 dígitos) | +| `:i_day` | Dia da publicação da postagem (sem zero à esquerda) | +| `:hour` | Published hour of posts (2-digit) | +| `:minute` | Published minute of posts (2-digit) | +| `:second` | Published second of posts (2-digit) | +| `:title` | Filename (relative to "source/\_posts/" folder) | +| `:name` | Filename | +| `:post_title` | Título da postagem | +| `:id` | ID da postagem (_not persistent across [cache reset](/pt-br/docs/commands#clean)_) | +| `:category` | Categorias. Se a postagem não possuir uma categoria, será usado o valor de `default_category`. | +| `:hash` | SHA1 hash of filename (same as `:title`) and date (12-hexadecimal) | Você pode definir o valor padrão de cada variável do permalink através da definição `permalink_defaults`: -``` yaml +```yaml permalink_defaults: lang: en ``` ### Exemplos -``` yaml source/_posts/hello-world.md +```yaml source/_posts/hello-world.md title: Hello World date: 2013-07-14 17:01:34 categories: -- foo -- bar + - foo + - bar ``` -Definição | Resultado ---- | --- -`:year/:month/:day/:title/` | 2013/07/14/hello-world/ -`:year-:month-:day-:title.html` | 2013-07-14-hello-world.html -`:category/:title/` | foo/bar/hello-world/ -`:title-:hash/` | hello-world-a2c8ac003b43/ +| Definição | Resultado | +| ------------------------------- | --------------------------- | +| `:year/:month/:day/:title/` | 2013/07/14/hello-world/ | +| `:year-:month-:day-:title.html` | 2013-07-14-hello-world.html | +| `:category/:title/` | foo/bar/hello-world/ | +| `:title-:hash/` | hello-world-a2c8ac003b43/ | -``` yaml source/_posts/lorem/hello-world.md +```yaml source/_posts/lorem/hello-world.md title: Hello World date: 2013-07-14 17:01:34 categories: -- foo -- bar + - foo + - bar ``` -Definição | Resultado ---- | --- -`:year/:month/:day/:title/` | 2013/07/14/lorem/hello-world/ -`:year/:month/:day/:name/` | 2013/07/14/hello-world/ +| Definição | Resultado | +| --------------------------- | ----------------------------- | +| `:year/:month/:day/:title/` | 2013/07/14/lorem/hello-world/ | +| `:year/:month/:day/:name/` | 2013/07/14/hello-world/ | ### Suporte Multi-idioma Para criar um site multi-idioma, você pode modificar as definições de `new_post_name` e `permalink` da seguinte forma: -``` yaml +```yaml new_post_name: :lang/:title.md permalink: :lang/:title/ ``` Quando você criar uma nova postagem, esta será salva em: -``` bash +```bash $ hexo new "Hello World" --lang tw # => source/_posts/tw/Hello-World.md ``` e a URL será: -``` plain +```plain http://localhost:4000/tw/hello-world/ ``` diff --git a/source/pt-br/docs/plugins.md b/source/pt-br/docs/plugins.md index 2be17eafba..69f9d37212 100644 --- a/source/pt-br/docs/plugins.md +++ b/source/pt-br/docs/plugins.md @@ -1,6 +1,7 @@ --- title: Plugins --- + O Hexo possui um poderoso sistema de plugins, o que facilita a extensão das funcionalidades sem modificar o código-fonte do módulo central. Existem dois tipos de plugins no Hexo: ### Script @@ -13,7 +14,7 @@ Se seu código é complicado ou se você deseja publicá-lo no registro do NPM, Seu novo diretório deve conter pelo menos dois arquivos: um contendo o código JavaScript e um arquivo `package.json` que descreve a finalidade do plugin e define suas dependências. -``` plain +```plain . ├── index.js └── package.json @@ -21,7 +22,7 @@ Seu novo diretório deve conter pelo menos dois arquivos: um contendo o código No mínimo, você deve definir as entradas `name`, `version` e `main` no `package.json`. Por exemplo: -``` json package.json +```json package.json { "name": "hexo-my-plugin", "version": "0.0.1", @@ -37,7 +38,7 @@ Você pode usar as ferramentas oficiais fornecidas pelo Hexo para acelerar o des - [hexo-fs]: Entrada/Saída (I/O) de arquivo - [hexo-util]: Utilitários -- [hexo-i18n]: Internacionalização (i18n) +- [hexo-i18n]: Internacionalização "i18n" - [hexo-pagination]: Gerar dados de paginação ### Publicando @@ -47,23 +48,21 @@ Quando o seu plug-in estiver pronto, você pode considerar publicá-lo na [lista 1. Fork [hexojs/site] 2. Clone o repositório no seu computador e instale as dependências. - {% code %} - $ git clone https://github.com/<username>/site.git - $ cd site - $ npm install - {% endcode %} + {% code %} + $ git clone https://github.com/<username>/site.git + $ cd site + $ npm install + {% endcode %} 3. Edite `source/_data/plugins.yml` e adicione seu plugin. Por exemplo: - {% code %} - - name: hexo-server - description: Server module for Hexo. - link: https://github.com/hexojs/hexo-server - tags: - - official - - server - - console - {% endcode %} + {% code %} + + - name: hexo-server + description: Server module for Hexo. + link: https://github.com/hexojs/hexo-server + tags: - official - server - console + {% endcode %} 4. Push para a branch. 5. Crie um pull request e descreva as modificações. diff --git a/source/pt-br/docs/server.md b/source/pt-br/docs/server.md index f222665409..14e22eabcf 100644 --- a/source/pt-br/docs/server.md +++ b/source/pt-br/docs/server.md @@ -6,19 +6,19 @@ title: Servidor Com o lançamento do Hexo 3, o servidor foi separado do módulo principal. Para começar a usar o servidor, primeiro você deve instalar o pacote [hexo-server]. -``` bash +```bash $ npm install hexo-server --save ``` Uma vez instalado o servidor, execute o comando a seguir para iniciar o servidor. Seu site será acessível em `http://localhost:4000` por padrão. Quando o servidor estiver sendo executado, o Hexo assistirá por alterações nos arquivos do projeto e atualizará automaticamente a página, por isso não é necessário reiniciar manualmente o servidor. -``` bash +```bash $ hexo server ``` Se você quiser mudar a porta ou se estiver encontrando erros `EADDRINUSE`, use a opção `-p` para configurar uma porta diferente. -``` bash +```bash $ hexo server -p 5000 ``` @@ -26,7 +26,7 @@ $ hexo server -p 5000 No modo estático, somente arquivos do diretório `public` serão servidos e nenhum arquivo será assistido por mudanças. Você deve executar `hexo generate` antes de iniciar o servidor. Em geral, é desta forma que o site é servido em produção. -``` bash +```bash $ hexo server -s ``` @@ -34,7 +34,7 @@ $ hexo server -s O Hexo executa o servidor em `0.0.0.0` por padrão. Você pode substituir a configuração de IP padrão. -``` bash +```bash $ hexo server -i 192.168.1.1 ``` @@ -44,7 +44,7 @@ $ hexo server -i 192.168.1.1 ### Instalaçãos -``` bash +```bash $ curl get.pow.cx | sh ``` @@ -52,7 +52,7 @@ $ curl get.pow.cx | sh Link simbólico no diretório `~/.pow` -``` bash +```bash $ cd ~/.pow $ ln -s /path/to/myapp ``` diff --git a/source/pt-br/docs/setup.md b/source/pt-br/docs/setup.md index 3b295d13d2..baae1b3cf1 100644 --- a/source/pt-br/docs/setup.md +++ b/source/pt-br/docs/setup.md @@ -6,7 +6,7 @@ title: Setup Uma vez instalado o Hexo, execute os seguintes comandos para inicializar um site com Hexo em um diretório `<folder>`. -``` bash +```bash $ hexo init <folder> $ cd <folder> $ npm install @@ -14,7 +14,7 @@ $ npm install Após inicializado, o diretório do seu projeto ficará com a seguinte estrutura: -``` plain +```plain . ├── _config.yml ├── package.json @@ -25,7 +25,7 @@ Após inicializado, o diretório do seu projeto ficará com a seguinte estrutura └── themes ``` -### _config.yml +### \_config.yml Arquivo de [configuração](configuration.html) do site. Você pode definir a maioria das configurações aqui. @@ -33,7 +33,7 @@ Arquivo de [configuração](configuration.html) do site. Você pode definir a ma Arquivo de dados da aplicação. Os renderizadores [Markdown](http://daringfireball.net/projects/markdown/), [EJS](https://ejs.co/) e [Stylus](http://learnboost.github.io/stylus/) são instalados por padrão. Se desejar, você pode desinstalá-los posteriormente. -``` json package.json +```json package.json { "name": "hexo-site", "version": "0.0.0", diff --git a/source/pt-br/docs/syntax-highlight.md b/source/pt-br/docs/syntax-highlight.md index 3f2765eed5..cc1327965e 100644 --- a/source/pt-br/docs/syntax-highlight.md +++ b/source/pt-br/docs/syntax-highlight.md @@ -17,7 +17,7 @@ code snippet code snippet {% endcode %} -``` [language] [title] [url] [link text] [additional options] +```[language] [title] [url] [link text] [additional options] code snippet ``` ```` @@ -35,7 +35,7 @@ highlight: auto_detect: false line_number: true line_threshold: 0 - tab_replace: '' + tab_replace: "" exclude_languages: - example wrap: true @@ -45,7 +45,7 @@ prismjs: preprocess: true line_number: true line_threshold: 0 - tab_replace: '' + tab_replace: "" ``` The YAML above is Hexo's default configuration. @@ -85,7 +85,7 @@ highlight: auto_detect: false line_number: true line_threshold: 0 - tab_replace: ' ' + tab_replace: " " exclude_languages: - example wrap: true @@ -116,18 +116,18 @@ Hexo adds line number by wrapping output inside `<figure>` and `<table>`: ```html <figure class="highlight yaml"> -<table> -<tbody> -<tr> - <td class="gutter"> - <pre><span class="line">1</span><br></pre> - </td> - <td class="code"> - <pre><span class="line"><span class="attr">hello:</span><span class="string">hexo</span></span><br></pre> - </td> -</tr> -</tbody> -</table> + <table> + <tbody> + <tr> + <td class="gutter"> + <pre><span class="line">1</span><br></pre> + </td> + <td class="code"> + <pre><span class="line"><span class="attr">hello:</span><span class="string">hexo</span></span><br></pre> + </td> + </tr> + </tbody> + </table> </figure> ``` @@ -143,7 +143,6 @@ Accepts an optional threshold to only show line numbers as long as the numbers o Replace tabs inside code block with given string. By default it is 2 spaces. - ### exclude_languages (+6.1.0) Only wrap with `<pre><code class="lang"></code></pre>` and will not render all tags(`span`, and `br`) in content if are languages matches this option. @@ -187,7 +186,7 @@ prismjs: preprocess: true line_number: true line_threshold: 0 - tab_replace: '' + tab_replace: "" ``` Prismjs is disabled by default. You should set `highlight.enable` to `false` before enabling prismjs. diff --git a/source/pt-br/docs/tag-plugins.md b/source/pt-br/docs/tag-plugins.md index 933ff25b15..6148925e48 100644 --- a/source/pt-br/docs/tag-plugins.md +++ b/source/pt-br/docs/tag-plugins.md @@ -86,14 +86,14 @@ code snippet Specify additional options in `option:value` format, e.g. `line_number:false first_line:5`. -Extra Options | Description | Default ---- | --- | --- -`line_number` | Show line number | `true` -`line_threshold` | Only show line numbers as long as the numbers of lines of the code block exceed such threshold. | `0` | -`highlight` | Enable code highlighting | `true` -`first_line` | Specify the first line number | `1` -`mark` | Line highlight specific line(s), each value separated by a comma. Specify number range using a dash<br>Example: `mark:1,4-7,10` will mark line 1, 4 to 7 and 10. | -`wrap` | Wrap the code block in [`<table>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table) | `true` +| Extra Options | Description | Default | +| ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| `line_number` | Show line number | `true` | +| `line_threshold` | Only show line numbers as long as the numbers of lines of the code block exceed such threshold. | `0` | +| `highlight` | Enable code highlighting | `true` | +| `first_line` | Specify the first line number | `1` | +| `mark` | Line highlight specific line(s), each value separated by a comma. Specify number range using a dash<br>Example: `mark:1,4-7,10` will mark line 1, 4 to 7 and 10. | +| `wrap` | Wrap the code block in [`<table>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table) | `true` | ### Exemplos @@ -143,7 +143,7 @@ _.compact([0, 1, false, 2, '', 3]); ``` {% codeblock _.compact http://underscorejs.org/#compact Underscore.js %} -_.compact([0, 1, false, 2, '', 3]); +\_.compact([0, 1, false, 2, '', 3]); => [1, 2, 3] {% endcodeblock %} @@ -152,9 +152,9 @@ _.compact([0, 1, false, 2, '', 3]); Isso é idêntico ao usar um bloco de código, mas usa três backticks (acentos grave) para delimitar o bloco. {% raw %} -``` [language] [title] [url] [link text] +`` [language] [title] [url] [link text] code snippet -``` +`` {% endraw %} ## Pull Quote @@ -323,32 +323,32 @@ _hexo-renderer-marked 3.1.0+ can (optionally) resolves the post's path of an ima `{% asset_img foo.jpg %}` -``` html -<img src="/2020/01/02/hello/foo.jpg"> +```html +<img src="/2020/01/02/hello/foo.jpg" /> ``` **Custom class** `{% asset_img post-image foo.jpg %}` -``` html -<img src="/2020/01/02/hello/foo.jpg" class="post-image"> +```html +<img src="/2020/01/02/hello/foo.jpg" class="post-image" /> ``` **Display size** `{% asset_img foo.jpg 500 400 %}` -``` html -<img src="/2020/01/02/hello/foo.jpg" width="500" height="400"> +```html +<img src="/2020/01/02/hello/foo.jpg" width="500" height="400" /> ``` **Title & Alt** `{% asset_img logo.svg "lorem ipsum'dolor'" %}` -``` html -<img src="/2020/01/02/hello/foo.jpg" title="lorem ipsum" alt="dolor"> +```html +<img src="/2020/01/02/hello/foo.jpg" title="lorem ipsum" alt="dolor" /> ``` ## Raw diff --git a/source/pt-br/docs/templates.md b/source/pt-br/docs/templates.md index efa895517a..a12497d62e 100644 --- a/source/pt-br/docs/templates.md +++ b/source/pt-br/docs/templates.md @@ -6,36 +6,40 @@ Os templates definem a apresentação do seu site, descrevendo o que cada págin {% youtube mb65bQ4iUc4 %} -Template | Página | Fallback ---- | --- | --- -`index` | Página Home | -`post` | Postagens | `index` -`page` | Páginas | `index` -`archive` | Arquivos (archives) | `index` -`category` | Categorias | `archive` -`tag` | Tags | `archive` +| Template | Página | Fallback | +| ---------- | ------------------- | --------- | +| `index` | Página Home | +| `post` | Postagens | `index` | +| `page` | Páginas | `index` | +| `archive` | Arquivos (archives) | `index` | +| `category` | Categorias | `archive` | +| `tag` | Tags | `archive` | ## Layouts Quando as páginas compartilham uma estrutura semelhante - por exemplo, quando dois templates possuem um cabeçalho e um rodapé - você pode considerar usar um `layout` para declarar essas semelhanças estruturais. Todo arquivo de layout deve conter uma variável `body` para exibir o conteúdo do template em questão. Por exemplo: -``` html index.ejs +```html index.ejs index ``` -``` html layout.ejs -<!DOCTYPE html> +```html layout.ejs +<!doctype html> <html> - <body><%- body %></body> + <body> + <%- body %> + </body> </html> ``` yields: -``` html -<!DOCTYPE html> +```html +<!doctype html> <html> - <body>index</body> + <body> + index + </body> </html> ``` @@ -45,18 +49,18 @@ Por padrão, o template de `layout` é usado por todos os outros templates. Voc Os partials são úteis para compartilhar componentes entre seus templates. Um exemplo típico inclui cabeçalhos (header), rodapés (footer) ou barras laterais (sidebar). Você pode querer colocar seus partials em arquivos separados para tornar a manutenção do seu site significativamente mais conveniente. Por exemplo: -``` html partial/header.ejs +```html partial/header.ejs <h1 id="logo"><%= config.title %></h1> ``` -``` html index.ejs +```html index.ejs <%- partial('partial/header') %> <div id="content">Home page</div> ``` yields: -``` html +```html <h1 id="logo">My Site</h1> <div id="content">Home page</div> ``` @@ -65,18 +69,18 @@ yields: Você pode definir variáveis locais em um template e usá-las em outros templates. -``` html partial/header.ejs +```html partial/header.ejs <h1 id="logo"><%= title %></h1> ``` -``` html index.ejs +```html index.ejs <%- partial('partial/header', {title: 'Hello World'}) %> <div id="content">Home page</div> ``` yields: -``` html +```html <h1 id="logo">Hello World</h1> <div id="content">Home page</div> ``` @@ -89,7 +93,7 @@ Este recurso foi emprestado do [Ruby on Rails](http://guides.rubyonrails.org/cac O recurso de `Fragment Caching` é melhor aproveitado em cabeçalhos, rodapés, barras laterais e outros conteúdos estáticos, onde sejam feitas pouquíssimas mudanças de um template para outro. Por exemplo: -``` js +```js <%- fragment_cache('header', function(){ return '<header></header>'; }); @@ -97,7 +101,7 @@ O recurso de `Fragment Caching` é melhor aproveitado em cabeçalhos, rodapés, Embora seja mais fácil usar partials: -``` js +```js <%- partial('header', {}, {cache: true}); ``` diff --git a/source/pt-br/docs/themes.md b/source/pt-br/docs/themes.md index 29c2944448..0ac0cd2b2d 100644 --- a/source/pt-br/docs/themes.md +++ b/source/pt-br/docs/themes.md @@ -6,7 +6,7 @@ title: Temas É fácil construir um tema para o Hexo - você só precisa criar um no diretório. Para começar a usar o seu tema, modifique a configuração `theme` do arquivo `_config.yml` do seu site. Um tema deve ter a seguinte estrutura: -``` plain +```plain . ├── _config.yml ├── languages @@ -15,7 +15,7 @@ title: Temas └── source ``` -### _config.yml +### \_config.yml Arquivo de configuração do tema. Unlike the site's primary configuration file, modificações neste arquivo não requerem uma reinicialização do servidor. @@ -27,7 +27,7 @@ Diretório de idiomas. Veja [internacionalização (i18n)](internationalization. Diretório de layouts. Este diretório contém os arquivos de template do tema, que definem a aparência do seu site. O Hexo fornece o mecanismo de template [Nunjucks] por padrão, mas você pode instalar plugins adicionais para suportar mecanismos alternativos, como [EJS], [Haml], [Jade] ou [Pug]. O Hexo escolhe o mecanismo de template com base na extensão do arquivo deste. Por exemplo: -``` plain +```plain layout.ejs - uses EJS layout.njk - uses Nunjucks ``` @@ -51,26 +51,26 @@ Quando você terminar de criar seu tema, você pode publicá-lo na [lista de tem 1. Faça um fork [hexojs/site] 2. Clone o repositório no seu computador e instale dependências. - ```shell - $ git clone https://github.com/<username>/site.git - $ cd site - $ npm install - ``` + ```shell + $ git clone https://github.com/<username>/site.git + $ cd site + $ npm install + ``` 3. Edite o arquivo `source/_data/themes.yml` e adicione seu tema. Por exemplo: - ```yaml - - name: landscape - description: A brand new default theme for Hexo. - link: https://github.com/hexojs/hexo-theme-landscape - preview: http://hexo.io/hexo-theme-landscape - tags: - - official - - responsive - - widget - - two_column - - one_column - ``` + ```yaml + - name: landscape + description: A brand new default theme for Hexo. + link: https://github.com/hexojs/hexo-theme-landscape + preview: http://hexo.io/hexo-theme-landscape + tags: + - official + - responsive + - widget + - two_column + - one_column + ``` 4. Adicione um print de tela (com o mesmo nome do tema) no diretório `source/themes/screenshots`. Deve ser um arquivo PNG com resolução de 800x500 pixels. 5. Faça um push para o seu repositório remoto. diff --git a/source/pt-br/docs/troubleshooting.md b/source/pt-br/docs/troubleshooting.md index b32f66500e..126eb490c2 100644 --- a/source/pt-br/docs/troubleshooting.md +++ b/source/pt-br/docs/troubleshooting.md @@ -1,18 +1,19 @@ --- title: Soluções de Problemas --- + No caso de você ter problemas com o uso do Hexo, aqui está uma lista de soluções para alguns dos problemas mais frequentes. Se esta página não ajudar a resolver seu problema, tente fazer uma pesquisa no nosso [GitHub](https://github.com/hexojs/hexo/issues) ou no nosso [Google Group](https://groups.google.com/group/hexo). ## YAML Parsing Error -``` plain +```plain JS-YAML: incomplete explicit mapping pair; a key node is missed at line 18, column 29: last_updated: Last updated: %s ``` Delimite a string com aspas duplas se ela contiver dois pontos (:). -``` plain +```plain JS-YAML: bad indentation of a mapping entry at line 18, column 31: last_updated:"Last updated: %s" ``` @@ -23,13 +24,13 @@ Para mais informações, veja [YAML Spec](http://www.yaml.org/spec/1.2/spec.html ## EMFILE Error -``` plain +```plain Error: EMFILE, too many open files ``` Embora o Node.js tenha I/O não bloqueante, o número máximo de I/O síncronas ainda é limitado pelo sistema. Você pode encontrar um erro EMFILE ao tentar gerar uma grande quantidade de arquivos. Você pode tentar executar o seguinte comando para aumentar o número de operações de I/O síncronas permitidas. -``` bash +```bash $ ulimit -n 10000 ``` @@ -37,7 +38,7 @@ $ ulimit -n 10000 If you encounter the following error: -``` bash +```bash $ ulimit -n 10000 ulimit: open files: cannot modify limit: Operation not permitted ``` @@ -48,23 +49,23 @@ To override the limit: 1. Add the following line to "/etc/security/limits.conf": - ``` - * - nofile 10000 +``` +* - nofile 10000 - # '*' applies to all users and '-' set both soft and hard limits - ``` +# '*' applies to all users and '-' set both soft and hard limits +``` - * The above setting may not apply in some cases, ensure "/etc/pam.d/login" and "/etc/pam.d/lightdm" have the following line. (Ignore this step if those files do not exist) +- The above setting may not apply in some cases, ensure "/etc/pam.d/login" and "/etc/pam.d/lightdm" have the following line. (Ignore this step if those files do not exist) - ``` - session required pam_limits.so - ``` +``` +session required pam_limits.so +``` 2. If you are on a [systemd-based](https://en.wikipedia.org/wiki/Systemd#Adoption) distribution, systemd may override "limits.conf". To set the limit in systemd, add the following line in "/etc/systemd/system.conf" and "/etc/systemd/user.conf": - ``` - DefaultLimitNOFILE=10000 - ``` +``` +DefaultLimitNOFILE=10000 +``` 3. Reboot @@ -86,7 +87,7 @@ Aumente o tamanho da memória heap do Node.js alterando a primeira linha de `hex ## Problemas de Deploy com Git -``` plain +```plain error: RPC failed; result=22, HTTP code = 403 fatal: 'username.github.io' does not appear to be a git repository @@ -96,19 +97,19 @@ Certifique-se de ter [configurado o git](https://help.github.com/articles/set-up ## Problemas de Servidor -``` plain +```plain Error: listen EADDRINUSE ``` Você pode ter iniciado dois servidores do Hexo ao mesmo tempo ou pode haver outro aplicativo usando a mesma porta. Tente modificar a configuração `port` ou iniciar o servidor do Hexo com o argumento `-p`. -``` bash +```bash $ hexo server -p 5000 ``` ## Problemas na Instalação de Plugins -``` plain +```plain npm ERR! node-waf configure build ``` @@ -143,7 +144,7 @@ A Hexo usa [Warehouse] para o seu modelo de dados. Ele não é um array, então Alguns dados não podem ser atualizados ou os arquivos recém-gerados são idênticos aos da última versão. Limpe o cache e tente novamente. -``` bash +```bash $ hexo clean ``` @@ -161,7 +162,7 @@ Quando você não consegue executar nenhum comando do Hexo, com exceção de `he ## Conteúdo Escapando -O Hexo usa [Nunjucks] para renderizar posts ([Swig] foi usado na versão mais antiga, que compartilha uma sintaxe semelhante). O conteúdo delimitado com `{{ }}` ou `{% %}` será "parseado" e pode causar problemas. Você pode empacotar um conteúdo sensível com a tag plugin [`raw`](/docs/tag-plugins#Raw), single backtick ```` `{{ }}` ```` or triple backtick. +O Hexo usa [Nunjucks] para renderizar posts ([Swig] foi usado na versão mais antiga, que compartilha uma sintaxe semelhante). O conteúdo delimitado com `{{ }}` ou `{% %}` será "parseado" e pode causar problemas. Você pode empacotar um conteúdo sensível com a tag plugin [`raw`](/docs/tag-plugins#Raw), single backtick `` `{{ }}` `` or triple backtick. Alternatively, Nunjucks tags can be disabled through the renderer's option (if supported), [API](/api/renderer#Disable-Nunjucks-tags) or [front-matter](/docs/front-matter). ``` @@ -186,7 +187,7 @@ Error: watch ENOSPC ... Isto pode ser consertado através do comando `$ npm dedupe` ou, se isso não funcionar, tente o seguinte comando no terminal do Linux: -``` bash +```bash $ echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p ``` @@ -202,7 +203,7 @@ Error: watch /path/to/hexo/theme/ EMPERM Infelizmente, o WSL (Windows Subsystem for Linux) atualmente não suporta os observadores (watchers) do sistema de arquivos. Portanto, o recurso de atualização em tempo real do servidor do Hexo não está disponível no momento. Contudo, ainda é possível executar o servidor a partir de um ambiente WSL, primeiro gere os arquivos e depois execute servidor em modo estático: -``` sh +```sh $ hexo generate $ hexo server -s ``` diff --git a/source/pt-br/docs/variables.md b/source/pt-br/docs/variables.md index 52df341101..68ca485c41 100644 --- a/source/pt-br/docs/variables.md +++ b/source/pt-br/docs/variables.md @@ -6,15 +6,15 @@ title: Variáveis ### Variáveis Globais -Variável | Descrição | Tipo ---- | --- | --- -`site` | Informações do site. | `object`; veja [Variáveis do Site] -`page` | Informações específicas da página e variáveis personalizadas definidas no front-matter. | `object`; veja [Variáveis da Página] -`config` | Configuração do site. | `object` (arquivo `_config` do seu site) -`theme` | Configuração do tema. Herda a configuração do site. | `object` (arquivo `_config` do seu tema) -`path` | Caminho da página atual | `string` -`url` | URL completa da página atual | `string` -`env` | Variáveis de ambiente | ??? +| Variável | Descrição | Tipo | +| -------- | --------------------------------------------------------------------------------------- | ---------------------------------------- | +| `site` | Informações do site. | `object`; veja [Variáveis do Site] | +| `page` | Informações específicas da página e variáveis personalizadas definidas no front-matter. | `object`; veja [Variáveis da Página] | +| `config` | Configuração do site. | `object` (arquivo `_config` do seu site) | +| `theme` | Configuração do tema. Herda a configuração do site. | `object` (arquivo `_config` do seu tema) | +| `path` | Caminho da página atual | `string` | +| `url` | URL completa da página atual | `string` | +| `env` | Variáveis de ambiente | ??? | {% note warn %} Lodash has been removed from global variables since Hexo 5.0.0. [You-Dont-Need-Lodash-Underscore](https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore) might be helpful for your migration. @@ -22,79 +22,79 @@ Lodash has been removed from global variables since Hexo 5.0.0. [You-Dont-Need-L ### Variáveis do Site -Variável | Descrição | Tipo ---- | --- | --- -`site.posts` | Todos as postagens | `array` de objetos `post` -`site.pages` | Todas as páginas | `array` de objetos `page` -`site.categories` | Todas as categorias | `array` de ??? -`site.tags` | Todas as tags | `array` de ??? +| Variável | Descrição | Tipo | +| ----------------- | ------------------- | ------------------------- | +| `site.posts` | Todos as postagens | `array` de objetos `post` | +| `site.pages` | Todas as páginas | `array` de objetos `page` | +| `site.categories` | Todas as categorias | `array` de ??? | +| `site.tags` | Todas as tags | `array` de ??? | ### Variáveis da Página **Artigo (`page`)** -Variável | Descrição | Tipo ---- | --- | --- -`page.title` | Título do artigo | `string` -`page.date` | Data de criação do artigo | [Moment.js] objeto -`page.updated` | Data da última atualização do artigo | [Moment.js] object -`page.comments` | Comentário habilitado ou não | `boolean` -`page.layout` | Nome do layout | `string` -`page.content` | O conteúdo completo processado do artigo | `string` -`page.excerpt` | Trecho do artigo| `string` -`page.more` | Conteúdo exceto trecho do artigo | `string` -`page.source` | O caminho do arquivo de fontes | `string` -`page.full_source` | Caminho completo do arquivo de fontes | `string` -`page.path` | A URL do artigo sem a URL raiz. Usamos geralmente `url_for(page.path)` no tema. | `string` -`page.permalink` | URL completa do artigo | `string` -`page.prev` | A postagem anterior, `null` se for a primeira postagem | ??? -`page.next` | A próxima postagem, `null` se for a última postagem | ??? -`page.raw` | Os dados brutos do artigo | ??? -`page.photos` | As fotos do artigo (Usado em postagens de galeria) | array de ??? -`page.link` | O link externo do artigo (Usado em postagens de link) | `string` +| Variável | Descrição | Tipo | +| ------------------ | ------------------------------------------------------------------------------- | ------------------ | +| `page.title` | Título do artigo | `string` | +| `page.date` | Data de criação do artigo | [Moment.js] objeto | +| `page.updated` | Data da última atualização do artigo | [Moment.js] object | +| `page.comments` | Comentário habilitado ou não | `boolean` | +| `page.layout` | Nome do layout | `string` | +| `page.content` | O conteúdo completo processado do artigo | `string` | +| `page.excerpt` | Trecho do artigo | `string` | +| `page.more` | Conteúdo exceto trecho do artigo | `string` | +| `page.source` | O caminho do arquivo de fontes | `string` | +| `page.full_source` | Caminho completo do arquivo de fontes | `string` | +| `page.path` | A URL do artigo sem a URL raiz. Usamos geralmente `url_for(page.path)` no tema. | `string` | +| `page.permalink` | URL completa do artigo | `string` | +| `page.prev` | A postagem anterior, `null` se for a primeira postagem | ??? | +| `page.next` | A próxima postagem, `null` se for a última postagem | ??? | +| `page.raw` | Os dados brutos do artigo | ??? | +| `page.photos` | As fotos do artigo (Usado em postagens de galeria) | array de ??? | +| `page.link` | O link externo do artigo (Usado em postagens de link) | `string` | **Post (`post`):** O mesmo que o layout `page` mas adicione as seguintes variáveis. -Variável | Descrição | Tipo ---- | --- | --- -`page.published` | Verdadeiro se a postagem não for um rascunho | `boolean` -`page.categories` | Todas as categorias da postagem | `array` de ??? -`page.tags` | Todas as tags da postagem | `array` de ??? +| Variável | Descrição | Tipo | +| ----------------- | -------------------------------------------- | -------------- | +| `page.published` | Verdadeiro se a postagem não for um rascunho | `boolean` | +| `page.categories` | Todas as categorias da postagem | `array` de ??? | +| `page.tags` | Todas as tags da postagem | `array` de ??? | **Home (`index`)** -Variável | Descrição | Tipo ---- | --- | --- -`page.per_page` | Postagens exibidas por página | `number` -`page.total` | Número total de páginas | `number` -`page.current` | Número da página atual | `number` -`page.current_url` | A URL da página atual | `string` -`page.posts` | Posts in this page ([Data Model](https://hexojs.github.io/warehouse/)) | -`page.prev` | Número da página anterior. `0` se a página atual for a primeira. | `number` -`page.prev_link` | A URL da página anterior. `''` se a página atual for a primeira. | `string` -`page.next` | Número da próxima página. `0` se a página atual for a última. | `number` -`page.next_link` | A URL da próxima página. `''` se a página atual for a última. | `string` -`page.path` | A URL da página atual sem URL raiz. Costumamos usar `url_for(page.path)` no tema. | `string` +| Variável | Descrição | Tipo | +| ------------------ | --------------------------------------------------------------------------------- | -------- | +| `page.per_page` | Postagens exibidas por página | `number` | +| `page.total` | Número total de páginas | `number` | +| `page.current` | Número da página atual | `number` | +| `page.current_url` | A URL da página atual | `string` | +| `page.posts` | Posts in this page ([Data Model](https://hexojs.github.io/warehouse/)) | +| `page.prev` | Número da página anterior. `0` se a página atual for a primeira. | `number` | +| `page.prev_link` | A URL da página anterior. `''` se a página atual for a primeira. | `string` | +| `page.next` | Número da próxima página. `0` se a página atual for a última. | `number` | +| `page.next_link` | A URL da próxima página. `''` se a página atual for a última. | `string` | +| `page.path` | A URL da página atual sem URL raiz. Costumamos usar `url_for(page.path)` no tema. | `string` | **Arquivo (`archive`):** O mesmo que o layout do `index`, mas adicione as seguintes variáveis. -Variável | Descrição | Tipo ---- | --- | --- -`page.archive` | Igual a `true` | `boolean` -`page.year` | Ano do arquivo (4 - dígitos) | `number` -`page.month` | Mês do arquivo (2 dígitos sem zeros à esquerda) | `number` +| Variável | Descrição | Tipo | +| -------------- | ----------------------------------------------- | --------- | +| `page.archive` | Igual a `true` | `boolean` | +| `page.year` | Ano do arquivo (4 - dígitos) | `number` | +| `page.month` | Mês do arquivo (2 dígitos sem zeros à esquerda) | `number` | **Categoria (`category`):** O mesmo que o layout do `index` mas adicione as seguintes variáveis. -Variável | Descrição | Tipo ---- | --- | --- -`page.category` | Nome da categoria | `string` +| Variável | Descrição | Tipo | +| --------------- | ----------------- | -------- | +| `page.category` | Nome da categoria | `string` | **Tag (`tag`):** O mesmo que o layout do `index` mas adicione as seguintes variáveis. -Variável | Descrição | Tipo ---- | --- | --- -`page.tag` | Nome da tag | `string` +| Variável | Descrição | Tipo | +| ---------- | ----------- | -------- | +| `page.tag` | Nome da tag | `string` | [Moment.js]: http://momentjs.com/ [Variáveis do Site]: #Variaveis-do-Site diff --git a/source/pt-br/docs/writing.md b/source/pt-br/docs/writing.md index c12f193dd8..5e5fa5e7d2 100644 --- a/source/pt-br/docs/writing.md +++ b/source/pt-br/docs/writing.md @@ -6,7 +6,7 @@ title: Escrevendo Para criar uma nova postagem ou uma nova página, você pode rodar o seguinte comando: -``` bash +```bash $ hexo new [layout] <title> ``` @@ -16,11 +16,11 @@ O `layout` padrão é o `post`, mas você pode fornecer o seu próprio. Você po Existem três layouts padrões no Hexo: `post`, `page` e `draft`. Os arquivos criados por cada um deles são salvos em um caminho diferente. As postagens criadas recentemente são salvas no diretório `source/_posts`. -Layout | Caminho ---- | --- -`post` | `source/_posts` -`page` | `source` -`draft` | `source/_drafts` +| Layout | Caminho | +| ------- | ---------------- | +| `post` | `source/_posts` | +| `page` | `source` | +| `draft` | `source/_drafts` | {% note tip Disabling layout %} If you don't want an article (post/page) to be processed with a theme, set `layout: false` in its front-matter. Refer to [this section](/docs/front-matter#Layout) for more details. @@ -30,20 +30,20 @@ If you don't want an article (post/page) to be processed with a theme, set `layo Por padrão, o Hexo usa o título da postagem como seu nome de arquivo. Você pode editar a configuração `new_post_name` em `_config.yml` para alterar o nome do arquivo padrão. Por exemplo, `:year-:month-:day-:title.md` prefixará nomes de arquivos com a data de criação de postagem. Você pode usar os seguintes placeholders: -Placeholder | Descrição ---- | --- -`:title` | Título do post (minúsculas, com espaços substituídos por hifens) -`:year` | Ano de criação, ex: `2015` -`:month` | Mês de criação (com zero à esquerda), ex: `04` -`:i_month` | Mês de criação (sem zero à esquerda), ex: `4` -`:day` | Dia de criação (com zero à esquerda), ex: `07` -`:i_day` | Dia de criação (sem zero à esquerda), ex: `7` +| Placeholder | Descrição | +| ----------- | ---------------------------------------------------------------- | +| `:title` | Título do post (minúsculas, com espaços substituídos por hifens) | +| `:year` | Ano de criação, ex: `2015` | +| `:month` | Mês de criação (com zero à esquerda), ex: `04` | +| `:i_month` | Mês de criação (sem zero à esquerda), ex: `4` | +| `:day` | Dia de criação (com zero à esquerda), ex: `07` | +| `:i_day` | Dia de criação (sem zero à esquerda), ex: `7` | ### Rascunhos Anteriormente, mencionamos um layout especial no Hexo: `draft`. As postagens inicializadas com este layout são salvas no diretório `source/_drafts`. Você pode usar o comando `publish` para mover os rascunhos para o diretório `source/_posts`. O comando `publish` funciona de forma semelhante ao comando `new`. -``` bash +```bash $ hexo publish [layout] <title> ``` @@ -53,17 +53,17 @@ Os rascunhos não são exibidos por padrão. Você pode adicionar a opção `--d Ao criar postagens, o Hexo irá construir arquivos com base no arquivo correspondente no diretório `scaffolds`. Por exemplo: -``` bash +```bash $ hexo new photo "My Gallery" ``` Quando você executa este comando, o Hexo tentará encontrar `photo.md` no diretório `scaffolds` e criar a postagem com base nele. Os seguintes placeholders estão disponíveis em scaffolds: -Placeholder | Descrição ---- | --- -`layout` | Layout -`title` | Título -`date` | Data de criação do arquivo +| Placeholder | Descrição | +| ----------- | -------------------------- | +| `layout` | Layout | +| `title` | Título | +| `date` | Data de criação do arquivo | ### Supported Formats diff --git a/source/ru/api/box.md b/source/ru/api/box.md index ee7d30984e..161adf507f 100644 --- a/source/ru/api/box.md +++ b/source/ru/api/box.md @@ -1,18 +1,19 @@ --- title: Модуль --- + Модуль представляет собой контейнер, используемый для обработки файлов в указанной папке. Hexo использует два модуля: `hexo.source` и `hexo.theme`. Первый используется для обработки папки с исходниками `source` с последующим применением указанной темы из папки `themes`. ## Обработка файлов (Load Files) Модули используют два способа загрузки файлов: `process` и `watch`. `process` обрабатывает все файлы в папке по команде. `watch` обрабатывает файлы при их изменении. -``` js -box.process().then(function(){ +```js +box.process().then(function () { // ... }); -box.watch().then(function(){ +box.watch().then(function () { // Можно вызвать команду box.unwatch() после, чтобы остановить отслеживание файлов. }); ``` @@ -21,7 +22,7 @@ box.watch().then(function(){ Модули поддерживают много способов для нахождения обрабатываемых папок. Можно использовать регулярные выражения, функции или строки шаблонов Express-style. Например: -``` plain +```plain posts/:id => posts/89 posts/*path => posts/2015/title ``` @@ -32,30 +33,30 @@ posts/*path => posts/2015/title Обработчик является важнейшим элементом модуля и служит для преобразования файлов. Можно использовать сопоставление папок, как описано выше, для ограничения обрабатываемых файлов. Новый обработчик добавляется методом `addProcessor` -``` js -box.addProcessor('posts/:id', function(file){ +```js +box.addProcessor("posts/:id", function (file) { // }); ``` Модуль передаёт содержимое соответствующих файлов обработчикам. Информацию можно читать прямо из аргумента `file` в обратный вызов (callback): -Свойство | Описание ---- | --- -`source` | Полный путь к файлу -`path` | Относительный путь к файлу модуля -`type` | Тип файла. Возможные значения `create`, `update`, `skip`, `delete`. -`params` | Информация о сопоставлении путей. +| Свойство | Описание | +| -------- | ------------------------------------------------------------------- | +| `source` | Полный путь к файлу | +| `path` | Относительный путь к файлу модуля | +| `type` | Тип файла. Возможные значения `create`, `update`, `skip`, `delete`. | +| `params` | Информация о сопоставлении путей. | Модуль содержит и другие методы, не нужно делать прямые вызовы к файлу самостоятельно. -Метод | Описание ---- | --- -`read` | Чтение файла -`readSync` | Синхронное чтение файла -`stat` | Получение статуса файла -`statSync` | Синхронное получение статуса файла -`render` | Обработка файла -`renderSync` | Синхронная обработка файла +| Метод | Описание | +| ------------ | ---------------------------------- | +| `read` | Чтение файла | +| `readSync` | Синхронное чтение файла | +| `stat` | Получение статуса файла | +| `statSync` | Синхронное получение статуса файла | +| `render` | Обработка файла | +| `renderSync` | Синхронная обработка файла | [util.Pattern]: https://github.com/hexojs/hexo-util#patternrule diff --git a/source/ru/api/console.md b/source/ru/api/console.md index 69284ce31e..3765dc142c 100644 --- a/source/ru/api/console.md +++ b/source/ru/api/console.md @@ -1,21 +1,22 @@ --- title: Консоль --- + Консоль служит для взаимодействия пользователей с Hexo. Регистрирует и описывает доступные консольные команды. ## Краткий обзор -``` js -hexo.extend.console.register(name, desc, options, function(args){ +```js +hexo.extend.console.register(name, desc, options, function (args) { // ... }); ``` -Свойство | Описание ---- | --- -`name` | Имя -`desc` | Описание -`options` | Опции +| Свойство | Описание | +| --------- | -------- | +| `name` | Имя | +| `desc` | Описание | +| `options` | Опции | Значение из аргумента `args` передаётся в функцию. Свойство описывает вводимые через терминал данные. Анализируется с помощью [Minimist]. @@ -25,8 +26,10 @@ hexo.extend.console.register(name, desc, options, function(args){ Добавление используемых команд в консоль. Например: -``` js -{usage: '[layout] <title>'} +```js +{ + usage: "[layout] <title>"; +} // hexo new [layout] <title> ``` @@ -34,12 +37,12 @@ hexo.extend.console.register(name, desc, options, function(args){ Описание аргументов в консоли. Например: -``` js +```js { arguments: [ - {name: 'layout', desc: 'Post layout'}, - {name: 'title', desc: 'Post title'} - ] + { name: "layout", desc: "Post layout" }, + { name: "title", desc: "Post title" }, + ]; } ``` @@ -47,11 +50,9 @@ hexo.extend.console.register(name, desc, options, function(args){ Описание опций в консоли. Например: -``` js +```js { - options: [ - {name: '-r, --replace', desc: 'Replace existing files'} - ] + options: [{ name: "-r, --replace", desc: "Replace existing files" }]; } ``` @@ -61,10 +62,14 @@ hexo.extend.console.register(name, desc, options, function(args){ ## Пример -``` js -hexo.extend.console.register('config', 'Display configuration', function(args){ - console.log(hexo.config); -}); +```js +hexo.extend.console.register( + "config", + "Display configuration", + function (args) { + console.log(hexo.config); + }, +); ``` [Minimist]: https://github.com/minimistjs/minimist diff --git a/source/ru/api/deployer.md b/source/ru/api/deployer.md index 9834a8b6f1..ad8adb4250 100644 --- a/source/ru/api/deployer.md +++ b/source/ru/api/deployer.md @@ -1,12 +1,13 @@ --- title: Инструмент размещения --- + Позволяет быстро развернуть свой сайт на удалённом сервере без сложных команд. ## Краткий обзор -``` js -hexo.extend.deployer.register(name, function(args){ +```js +hexo.extend.deployer.register(name, function (args) { // ... }); ``` diff --git a/source/ru/api/events.md b/source/ru/api/events.md index bfe97b166c..536e7d6afe 100644 --- a/source/ru/api/events.md +++ b/source/ru/api/events.md @@ -1,6 +1,7 @@ --- title: События --- + Hexo унаследован от сборщика событий [EventEmitter]. Используйте метод `on` для просмотра событий Hexo и метод `emit` для генерации событий. Более подробную информацию смотрите в документации Node.js API. ### deployBefore @@ -27,16 +28,16 @@ Hexo унаследован от сборщика событий [EventEmitter]. Вызывается после того, как пост создан. Событие возвращает данные поста: -``` js -hexo.on('new', function(post){ +```js +hexo.on("new", function (post) { // }); ``` -Данные | Описание ---- | --- -`post.path` | Полный путь к файлу поста -`post.content` | Содержание файла поста +| Данные | Описание | +| -------------- | ------------------------- | +| `post.path` | Полный путь к файлу поста | +| `post.content` | Содержание файла поста | ### processBefore diff --git a/source/ru/api/filter.md b/source/ru/api/filter.md index fbf6b5c0e0..24c858e06a 100644 --- a/source/ru/api/filter.md +++ b/source/ru/api/filter.md @@ -1,11 +1,12 @@ --- title: Фильтры --- + Фильтры используются для изменения указанных данных. Hexo передает данные для фильтров в определенной последовательности и фильтров изменения данных один за другим. Эта концепция была заимствована из [WordPress](http://codex.wordpress.org/Plugin_API#Filters) ## Краткий обзор -``` js +```js hexo.extend.filter.register(type, function() { // User configuration const { config } = this; @@ -22,69 +23,69 @@ hexo.extend.filter.register(type, function() { ## Использование фильтров -``` js +```js hexo.extend.filter.exec(type, data, options); hexo.extend.filter.execSync(type, data, options); ``` -Опция | Описание ---- | --- -`context` | Контекст -`args` | Аргументы. Должны быть в виде массива. +| Опция | Описание | +| --------- | -------------------------------------- | +| `context` | Контекст | +| `args` | Аргументы. Должны быть в виде массива. | Первый аргумент, передаваемый в каждый фильтр, это `data`. Данные `data`, передаваемые в следующий фильтр, могут быть изменены путем возврата нового значения. Если же ничего не возвращается, данные остаются без изменений. Вы даже можете использовать аргументы, чтобы указать другие аргументы в фильтрах. Например: -``` js -hexo.extend.filter.register('test', function(data, arg1, arg2){ +```js +hexo.extend.filter.register("test", function (data, arg1, arg2) { // data === 'some data' // arg1 === 'foo' // arg2 === 'bar' - return 'something'; + return "something"; }); -hexo.extend.filter.register('test', function(data, arg1, arg2){ +hexo.extend.filter.register("test", function (data, arg1, arg2) { // data === 'something' }); -hexo.extend.filter.exec('test', 'some data', { - args: ['foo', 'bar'] +hexo.extend.filter.exec("test", "some data", { + args: ["foo", "bar"], }); ``` Также можно использовать следующие методы для выполнения фильтров: -``` js +```js hexo.execFilter(type, data, options); hexo.execFilterSync(type, data, options); ``` ## Отмена фильтров -``` js +```js hexo.extend.filter.unregister(type, filter); ``` **Example** -``` js +```js // Unregister a filter which is registered with named function const filterFn = (data) => { - data = 'something'; + data = "something"; return data; }; -hexo.extend.filter.register('example', filterFn); +hexo.extend.filter.register("example", filterFn); -hexo.extend.filter.unregister('example', filterFn); +hexo.extend.filter.unregister("example", filterFn); ``` -``` js +```js // Unregister a filter which is registered with commonjs module -hexo.extend.filter.register('example', require('path/to/filter')); +hexo.extend.filter.register("example", require("path/to/filter")); -hexo.extend.filter.unregister('example', require('path/to/filter')); +hexo.extend.filter.unregister("example", require("path/to/filter")); ``` ## Список фильтров @@ -97,8 +98,8 @@ hexo.extend.filter.unregister('example', require('path/to/filter')); Например, перевести название в нижний регистр: -``` js -hexo.extend.filter.register('before_post_render', function(data){ +```js +hexo.extend.filter.register("before_post_render", function (data) { data.title = data.title.toLowerCase(); return data; }); @@ -110,9 +111,12 @@ hexo.extend.filter.register('before_post_render', function(data){ Например, чтобы заменить `@username` ссылкой на профиль в Twitter: -``` js -hexo.extend.filter.register('after_post_render', function(data){ - data.content = data.content.replace(/@(\d+)/, '<a href="http://twitter.com/$1">#$1</a>'); +```js +hexo.extend.filter.register("after_post_render", function (data) { + data.content = data.content.replace( + /@(\d+)/, + '<a href="http://twitter.com/$1">#$1</a>', + ); return data; }); ``` @@ -121,8 +125,8 @@ hexo.extend.filter.register('after_post_render', function(data){ Выполняется перед выходом из Hexo. Срабатывает сразу после выполнения `hexo.exit`. -``` js -hexo.extend.filter.register('before_exit', function(){ +```js +hexo.extend.filter.register("before_exit", function () { // ... }); ``` @@ -131,8 +135,8 @@ hexo.extend.filter.register('before_exit', function(){ Выполнится перед началом генерации. -``` js -hexo.extend.filter.register('before_generate', function(){ +```js +hexo.extend.filter.register("before_generate", function () { // ... }); ``` @@ -141,8 +145,8 @@ hexo.extend.filter.register('before_generate', function(){ Выполнится после окончания генерации. -``` js -hexo.extend.filter.register('after_generate', function(){ +```js +hexo.extend.filter.register("after_generate", function () { // ... }); ``` @@ -153,8 +157,8 @@ hexo.extend.filter.register('after_generate', function(){ Например, чтобы добавить переменную текущего времени в шаблон: -``` js -hexo.extend.filter.register('template_locals', function(locals){ +```js +hexo.extend.filter.register("template_locals", function (locals) { locals.now = Date.now(); return locals; }); @@ -164,8 +168,8 @@ hexo.extend.filter.register('template_locals', function(locals){ Выполнится после начала инициализации Hexo - запустится только после того, как полностью отработает команда `hexo.init`. -``` js -hexo.extend.filter.register('after_init', function(){ +```js +hexo.extend.filter.register("after_init", function () { // ... }); ``` @@ -174,8 +178,8 @@ hexo.extend.filter.register('after_init', function(){ Используется при создании поста для определения пути постоянной ссылки. -``` js -hexo.extend.filter.register('new_post_path', function(data, replace){ +```js +hexo.extend.filter.register("new_post_path", function (data, replace) { // ... }); ``` @@ -184,8 +188,8 @@ hexo.extend.filter.register('new_post_path', function(data, replace){ Выполняется при создании поста для определения пути постоянной ссылки. -``` js -hexo.extend.filter.register('post_permalink', function(data){ +```js +hexo.extend.filter.register("post_permalink", function (data) { // ... }); ``` @@ -200,10 +204,10 @@ hexo.extend.filter.register('post_permalink', function(data){ Например, чтобы добавить `X-Powered-By: Hexo` в заголовке ответа: -``` js -hexo.extend.filter.register('server_middleware', function(app){ - app.use(function(req, res, next){ - res.setHeader('X-Powered-By', 'Hexo'); +```js +hexo.extend.filter.register("server_middleware", function (app) { + app.use(function (req, res, next) { + res.setHeader("X-Powered-By", "Hexo"); next(); }); }); diff --git a/source/ru/api/generator.md b/source/ru/api/generator.md index e91d91d8a5..da7f7061aa 100644 --- a/source/ru/api/generator.md +++ b/source/ru/api/generator.md @@ -1,12 +1,13 @@ --- title: Генератор --- + Генератор создаёт ссылки на основе обработанных файлов. ## Краткий обзор -``` js -hexo.extend.generator.register(name, function(locals){ +```js +hexo.extend.generator.register(name, function (locals) { // ... }); ``` @@ -15,27 +16,27 @@ hexo.extend.generator.register(name, function(locals){ ## Обновление путей -``` js -hexo.extend.generator.register('test', function(locals){ +```js +hexo.extend.generator.register("test", function (locals) { // Object return { - path: 'foo', - data: 'foo' + path: "foo", + data: "foo", }; // Array return [ - {path: 'foo', data: 'foo'}, - {path: 'bar', data: 'bar'} + { path: "foo", data: "foo" }, + { path: "bar", data: "bar" }, ]; }); ``` -Атрибут | Описание ---- | --- -`path` | Путь не включает префикс `/`. -`data` | Данные -`layout` | Макет. Укажите макеты для рендеринга. Значение может быть строкой или массивом. Если это проигнорировать, то путь будет возвращать данные `data` напрямую. +| Атрибут | Описание | +| -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `path` | Путь не включает префикс `/`. | +| `data` | Данные | +| `layout` | Макет. Укажите макеты для рендеринга. Значение может быть строкой или массивом. Если это проигнорировать, то путь будет возвращать данные `data` напрямую. | Когда исходные файлы обновляются, Hexo выполняет генерацию и пересоздаёт ссылки. **Пожалуйста, генерируйте данные, а не создавайте ссылки напрямую.** @@ -47,13 +48,13 @@ hexo.extend.generator.register('test', function(locals){ Далее устанавливается атрибут `layout` для рендеринга шаблонов. В этом примере два варианта: если макета для `archive` нет, будет использоваться макет `index`. -``` js -hexo.extend.generator.register('archive', function(locals){ +```js +hexo.extend.generator.register("archive", function (locals) { return { - path: 'archives/index.html', + path: "archives/index.html", data: locals.posts, - layout: ['archive', 'index'] - } + layout: ["archive", "index"], + }; }); ``` @@ -61,14 +62,14 @@ hexo.extend.generator.register('archive', function(locals){ Можно использовать удобный официальный инструмент [hexo-pagination] для легкого создания страниц с постраничной нумерацией. -``` js -var pagination = require('hexo-pagination'); +```js +var pagination = require("hexo-pagination"); -hexo.extend.generator.register('archive', function(locals){ - return pagination('archives/index.html', locals.posts, { +hexo.extend.generator.register("archive", function (locals) { + return pagination("archives/index.html", locals.posts, { perPage: 10, - layout: ['archive', 'index'], - data: {} + layout: ["archive", "index"], + data: {}, }); }); ``` @@ -77,13 +78,13 @@ hexo.extend.generator.register('archive', function(locals){ Перебирает все посты из переменной `locals.posts` и создаёт пути для всех найденных. -``` js -hexo.extend.generator.register('post', function(locals){ - return locals.posts.map(function(post){ +```js +hexo.extend.generator.register("post", function (locals) { + return locals.posts.map(function (post) { return { path: post.path, data: post, - layout: 'post' + layout: "post", }; }); }); @@ -93,15 +94,15 @@ hexo.extend.generator.register('post', function(locals){ На этот раз данные не возвращаются явно, вместо этого данные `data` отправляются в функцию, чтобы `fs.ReadStream` вызывался только при необходимости. -``` js -var fs = require('hexo-fs'); +```js +var fs = require("hexo-fs"); -hexo.extend.generator.register('asset', function(locals){ +hexo.extend.generator.register("asset", function (locals) { return { - path: 'file.txt', - data: function(){ - return fs.createReadStream('path/to/file.txt') - } + path: "file.txt", + data: function () { + return fs.createReadStream("path/to/file.txt"); + }, }; }); ``` diff --git a/source/ru/api/helper.md b/source/ru/api/helper.md index f8e0ecb6ca..d855f53779 100644 --- a/source/ru/api/helper.md +++ b/source/ru/api/helper.md @@ -1,25 +1,26 @@ --- title: Помощник --- + Помощник позволяет легко и быстро добавлять фрагменты кода в шаблоны. Мы рекомендуем использовать помощников в шаблонах, когда вы имеете дело со сложным кодом. ## Краткий обзор -``` js -hexo.extend.helper.register(name, function(){ +```js +hexo.extend.helper.register(name, function () { // ... }); ``` ## Пример -``` js -hexo.extend.helper.register('js', function(path){ +```js +hexo.extend.helper.register("js", function (path) { return '<script src="' + path + '"></script>'; }); ``` -``` js +```js <%- js('script.js') %> // <script src="script.js"></script> ``` @@ -34,8 +35,8 @@ hexo.extend.helper.register('js', function(path){ Все помощники выполняются в одном и том же окружении. Например, чтобы использовать [`url_for()`](/ru/docs/helpers#url-for) внутри собственного помощника: -``` js -hexo.extend.helper.register('lorem', function(path) { +```js +hexo.extend.helper.register("lorem", function (path) { return '<script src="' + this.url_for(path) + '"></script>'; }); ``` @@ -44,6 +45,6 @@ hexo.extend.helper.register('lorem', function(path) { `hexo.extend.helper.get` вернёт вспомогательную функцию, но в качестве контекста она должна иметь hexo, поэтому: -``` js -const url_for = hexo.extend.helper.get('url_for').bind(hexo); +```js +const url_for = hexo.extend.helper.get("url_for").bind(hexo); ``` diff --git a/source/ru/api/index.md b/source/ru/api/index.md index f5743257e3..79e0cbfe0c 100644 --- a/source/ru/api/index.md +++ b/source/ru/api/index.md @@ -1,6 +1,7 @@ --- title: API --- + Эта документация содержит подробную информацию об API и будет особенно полезна для людей, желающих изменить исходный код Hexo или писать новые плагины. Если Вас интересуют основы использования Hexo, пожалуйста, используйте [документацию](../docs). Обратите внимание, эта документация действительна только для Hexo 3 и выше. @@ -9,21 +10,21 @@ title: API Во-первых, нужно создать экземпляр Hexo. Он принимает два аргумента: корневой каталог сайта `base_dir` и объект, содержащий параметры инициализации. Далее для инициализации выполняется метод `init`, он вызывает Hexo и загружает настройки и плагины. -``` js -var Hexo = require('hexo'); +```js +var Hexo = require("hexo"); var hexo = new Hexo(process.cwd(), {}); -hexo.init().then(function(){ +hexo.init().then(function () { // ... }); ``` -Опция | Описание | Значение по умолчанию ---- | --- | --- -`debug` | Включает режим отладки. Отображает отладочные сообщения в консоль и сохраняет в файл `debug.log`, находящийся в корневой директории. | `false` -`safe` | Включает безопасный режим. Пропускается загрузка всех плагинов. | `false` -`silent` | Включает тихий режим. Скрывает отображение любых сообщений в терминале. | `false` -`config` | Указывает путь к файлу конфигурации. | `_config.yml` +| Опция | Описание | Значение по умолчанию | +| -------- | ------------------------------------------------------------------------------------------------------------------------------------ | --------------------- | +| `debug` | Включает режим отладки. Отображает отладочные сообщения в консоль и сохраняет в файл `debug.log`, находящийся в корневой директории. | `false` | +| `safe` | Включает безопасный режим. Пропускается загрузка всех плагинов. | `false` | +| `silent` | Включает тихий режим. Скрывает отображение любых сообщений в терминале. | `false` | +| `config` | Указывает путь к файлу конфигурации. | `_config.yml` | ## Загрузка файлов @@ -31,12 +32,12 @@ Hexo предусматривает два способа загрузки фа Оба метода позволяют загрузить список файлов и передать их в соответствующие обработчики. После того, как все файлы будут обработаны, они вызовут генератор создания ссылок. -``` js -hexo.load().then(function(){ +```js +hexo.load().then(function () { // ... }); -hexo.watch().then(function(){ +hexo.watch().then(function () { // Можно использовать hexo.unwatch() позже для отмены отслеживания изменений в файлах. }); ``` @@ -45,8 +46,8 @@ hexo.watch().then(function(){ Любую консольную команду можно вызвать явно с помощью метода `call` в экземпляре Hexo. Такой вызов принимает два аргумента: команду и её опции. Для каждой команды доступны свои опции. -``` js -hexo.call('generate', {}).then(function(){ +```js +hexo.call("generate", {}).then(function () { // ... }); ``` @@ -55,10 +56,13 @@ hexo.call('generate', {}).then(function(){ После успешного или неудачного завершения команд в консоли нужно вызывать метод `exit`. Это позволяет Hexo корректно завершить и закончить важные задачи, например, сохранение базы данных. -``` js -hexo.call('generate').then(function(){ - return hexo.exit(); -}).catch(function(err){ - return hexo.exit(err); -}); +```js +hexo + .call("generate") + .then(function () { + return hexo.exit(); + }) + .catch(function (err) { + return hexo.exit(err); + }); ``` diff --git a/source/ru/api/injector.md b/source/ru/api/injector.md index b317fd003c..dcf9383b88 100644 --- a/source/ru/api/injector.md +++ b/source/ru/api/injector.md @@ -1,12 +1,13 @@ --- title: Инъектор --- + Инъектор используется для добавления статического фрагмента кода в `<head>` и/или `<body>` генерируемых HTML-файлов. Hexo производит вставку **до того, как** будет выполнен фильтр `after_render:html`. ## Краткий обзор ```js -hexo.extend.injector.register(entry, value, to) +hexo.extend.injector.register(entry, value, to); ``` ### ввод `<string>` @@ -39,24 +40,34 @@ hexo.extend.injector.register(entry, value, to) - `tag`: Вставка произведётся только на страницы тегов (у которых переменная `is_tag()` является `true`) - Также можно использовать пользовательское имя макета, см. [Запись - Макет](/docs/writing#Layout). ----- +--- -Существуют и другие внутренние функции, см. [hexojs/hexo#4049](https://github.com/hexojs/hexo/pull/4049 ) для получения более подробной информации. +Существуют и другие внутренние функции, см. [hexojs/hexo#4049](https://github.com/hexojs/hexo/pull/4049) для получения более подробной информации. ## Пример ```js -const css = hexo.extend.helper.get('css').bind(hexo); -const js = hexo.extend.helper.get('js').bind(hexo); - -hexo.extend.injector.register('head_end', () => { - return css('https://cdn.jsdelivr.net/npm/aplayer@1.10.1/dist/APlayer.min.css'); -}, 'music'); - -hexo.extend.injector.register('body_end', '<script src="https://cdn.jsdelivr.net/npm/aplayer@1.10.1/dist/APlayer.min.js">', 'music'); - -hexo.extend.injector.register('body_end', () => { - return js('/js/jquery.js'); +const css = hexo.extend.helper.get("css").bind(hexo); +const js = hexo.extend.helper.get("js").bind(hexo); + +hexo.extend.injector.register( + "head_end", + () => { + return css( + "https://cdn.jsdelivr.net/npm/aplayer@1.10.1/dist/APlayer.min.css", + ); + }, + "music", +); + +hexo.extend.injector.register( + "body_end", + '<script src="https://cdn.jsdelivr.net/npm/aplayer@1.10.1/dist/APlayer.min.js">', + "music", +); + +hexo.extend.injector.register("body_end", () => { + return js("/js/jquery.js"); }); ``` @@ -68,10 +79,10 @@ hexo.extend.injector.register('body_end', () => { 1. -``` js -const css = hexo.extend.helper.get('css').bind(hexo); +```js +const css = hexo.extend.helper.get("css").bind(hexo); -hexo.extend.injector.register('head_end', () => { +hexo.extend.injector.register("head_end", () => { const { cssPath } = hexo.config.fooPlugin; return css(cssPath); }); @@ -79,23 +90,23 @@ hexo.extend.injector.register('head_end', () => { 2. -``` js index.js +```js index.js /* global hexo */ -hexo.extend.injector.register('head_end', require('./lib/inject').bind(hexo)) +hexo.extend.injector.register("head_end", require("./lib/inject").bind(hexo)); ``` -``` js lib/inject.js +```js lib/inject.js module.exports = function () { - const css = this.extend.helper.get('css'); + const css = this.extend.helper.get("css"); const { cssPath } = this.config.fooPlugin; return css(cssPath); -} +}; ``` -``` js lib/inject.js +```js lib/inject.js function injectFn() { - const css = this.extend.helper.get('css'); + const css = this.extend.helper.get("css"); const { cssPath } = this.config.fooPlugin; return css(cssPath); } @@ -105,23 +116,23 @@ module.exports = injectFn; 3. -``` js index.js +```js index.js /* global hexo */ -hexo.extend.injector.register('head_end', require('./lib/inject')(hexo)) +hexo.extend.injector.register("head_end", require("./lib/inject")(hexo)); ``` -``` js lib/inject.js +```js lib/inject.js module.exports = (hexo) => () => { - const css = hexo.extend.helper.get('css').bind(hexo); + const css = hexo.extend.helper.get("css").bind(hexo); const { cssPath } = hexo.config.fooPlugin; return css(cssPath); }; ``` -``` js lib/inject.js +```js lib/inject.js const injectFn = (hexo) => { - const css = hexo.extend.helper.get('css').bind(hexo); + const css = hexo.extend.helper.get("css").bind(hexo); const { cssPath } = hexo.config.fooPlugin; return css(cssPath); }; diff --git a/source/ru/api/locals.md b/source/ru/api/locals.md index 73c1ab2913..e3dde2a9b6 100644 --- a/source/ru/api/locals.md +++ b/source/ru/api/locals.md @@ -1,26 +1,27 @@ --- title: Локальные переменные --- + Локальные переменные используются для рендеринга шаблона, они доступны через переменную `site` в шаблоне. ## Переменные по умолчанию -Переменная | Описание ---- | --- -`posts` | Все посты -`pages` | Все страницы -`categories` | Все категории -`tags` | Все теги +| Переменная | Описание | +| ------------ | ------------- | +| `posts` | Все посты | +| `pages` | Все страницы | +| `categories` | Все категории | +| `tags` | Все теги | ## Получение переменной -``` js -hexo.locals.get('posts') +```js +hexo.locals.get("posts"); ``` ## Установка переменной -``` js +```js hexo.locals.set('posts', function(){ return ... }); @@ -28,18 +29,19 @@ hexo.locals.set('posts', function(){ ## Удаление переменной -``` js -hexo.locals.remove('posts'); +```js +hexo.locals.remove("posts"); ``` ## Получение всех переменных -``` js +```js hexo.locals.toObject(); ``` ## Очистка кэша -``` js +```js hexo.locals.invalidate(); -`` +``; +``` diff --git a/source/ru/api/migrator.md b/source/ru/api/migrator.md index e6b5d54a58..c539b761e2 100644 --- a/source/ru/api/migrator.md +++ b/source/ru/api/migrator.md @@ -1,12 +1,13 @@ --- title: Мигратор --- + Мигратор позволяет переходить на Hexo из других систем. ## Краткий обзор -``` js -hexo.extend.migrator.register(name, function(args){ +```js +hexo.extend.migrator.register(name, function (args) { // ... }); ``` diff --git a/source/ru/api/posts.md b/source/ru/api/posts.md index 7682611111..25a301181d 100644 --- a/source/ru/api/posts.md +++ b/source/ru/api/posts.md @@ -1,55 +1,56 @@ --- title: Посты --- + ## Создание поста -``` js +```js hexo.post.create(data, replace); ``` -Аргумент | Описание ---- | --- -`data` | Данные -`replace` | Заменять существующие файлы +| Аргумент | Описание | +| --------- | --------------------------- | +| `data` | Данные | +| `replace` | Заменять существующие файлы | Атрибуты поста можно установить в переменной `data`. Таблица ниже не является полной. Дополнительные атрибуты могут быть добавлены в шапке поста. -Данные | Описание ---- | --- -`title` | Заголовок -`slug` | Ссылка -`layout` | Шаблон. По умолчанию в настройках указано `default_layout`. -`path` | Путь. По умолчанию Hexo строит пути на основе переменной `new_post_path`, указанной в настройках. -`date` | Дата. По умолчанию — текущая дата. +| Данные | Описание | +| -------- | ------------------------------------------------------------------------------------------------- | +| `title` | Заголовок | +| `slug` | Ссылка | +| `layout` | Шаблон. По умолчанию в настройках указано `default_layout`. | +| `path` | Путь. По умолчанию Hexo строит пути на основе переменной `new_post_path`, указанной в настройках. | +| `date` | Дата. По умолчанию — текущая дата. | ## Публикация черновиков -``` js +```js hexo.post.publish(data, replace); ``` -Аргумент | Описание ---- | --- -`data` | Дата -`replace` | Заменять существующие файлы +| Аргумент | Описание | +| --------- | --------------------------- | +| `data` | Дата | +| `replace` | Заменять существующие файлы | Атрибуты поста можно установить в переменной `data`. Таблица ниже не является полной. Дополнительные атрибуты могут быть добавлены в шапке поста. -Данные | Описание ---- | --- -`slug` | Имя файла (Обязательно) -`layout` | Шаблон. По умолчанию берется из переменной `default_layout`, указанной в настройках. +| Данные | Описание | +| -------- | ------------------------------------------------------------------------------------ | +| `slug` | Имя файла (Обязательно) | +| `layout` | Шаблон. По умолчанию берется из переменной `default_layout`, указанной в настройках. | ## Обработка -``` js +```js hexo.post.render(source, data); ``` -Аргумент | Описание ---- | --- -`source` | Полный путь к файлу (необязательно) -`data` | Данные +| Аргумент | Описание | +| -------- | ----------------------------------- | +| `source` | Полный путь к файлу (необязательно) | +| `data` | Данные | Данные должны содержать атрибут `content`. Если нет, Hexo постарается прочитать исходный файл. Этапы выполнения этой функции следующие: diff --git a/source/ru/api/processor.md b/source/ru/api/processor.md index 20570e3fee..0c26eaae44 100644 --- a/source/ru/api/processor.md +++ b/source/ru/api/processor.md @@ -1,13 +1,14 @@ --- title: Обработчик --- + Обработчик используется для обработки исходных файлов в папке `source`. ## Краткий обзор -``` js -hexo.extend.processor.register(rule, function(file){ - // ... +```js +hexo.extend.processor.register(rule, function (file) { + // ... }); ``` diff --git a/source/ru/api/renderer.md b/source/ru/api/renderer.md index 44c2158785..2422ddb5b5 100644 --- a/source/ru/api/renderer.md +++ b/source/ru/api/renderer.md @@ -1,70 +1,85 @@ --- title: Рендер --- + Рендер используется для создания содержимого. ## Краткий обзор -``` js -hexo.extend.renderer.register(name, output, function(data, options){ - // ... -}, sync); +```js +hexo.extend.renderer.register( + name, + output, + function (data, options) { + // ... + }, + sync, +); ``` -Аргумент | Описание ---- | --- -`name` | Вводится расширение входного файла (нижний регистр, без ведущей `.`) -`output` | Выводится расширение входного файла (нижний регистр, без ведущей `.`) -`sync` | Режим синхронизации +| Аргумент | Описание | +| -------- | --------------------------------------------------------------------- | +| `name` | Вводится расширение входного файла (нижний регистр, без ведущей `.`) | +| `output` | Выводится расширение входного файла (нижний регистр, без ведущей `.`) | +| `sync` | Режим синхронизации | В функцию рендера передаются два аргумента: -Аргумент | Описание ---- | --- -`data` | Включает два атрибута: путь к файлу `path` и содержимое файла `text`. Переменная `path` не является обязательной. -`option` | Опции +| Аргумент | Описание | +| -------- | ----------------------------------------------------------------------------------------------------------------- | +| `data` | Включает два атрибута: путь к файлу `path` и содержимое файла `text`. Переменная `path` не является обязательной. | +| `option` | Опции | ## Пример ### Асинхронный режим -``` js -var stylus = require('stylus'); +```js +var stylus = require("stylus"); // Обратный вызов -hexo.extend.renderer.register('styl', 'css', function(data, options, callback){ - stylus(data.text).set('filename', data.path).render(callback); -}); +hexo.extend.renderer.register( + "styl", + "css", + function (data, options, callback) { + stylus(data.text).set("filename", data.path).render(callback); + }, +); // Запрос -hexo.extend.renderer.register('styl', 'css', function(data, options){ - return new Promise(function(resolve, reject){ - resolve('test'); +hexo.extend.renderer.register("styl", "css", function (data, options) { + return new Promise(function (resolve, reject) { + resolve("test"); }); }); ``` ### Синхронный режим -``` js -var ejs = require('ejs'); - -hexo.extend.renderer.register('ejs', 'html', function(data, options){ - options.filename = data.path; - return ejs.render(data.text, options); -}, true); +```js +var ejs = require("ejs"); + +hexo.extend.renderer.register( + "ejs", + "html", + function (data, options) { + options.filename = data.path; + return ejs.render(data.text, options); + }, + true, +); ``` ### Disable Nunjucks tags Nunjucks tags `{{ }}` or `{% %}` (utilized by [tag plugin](/docs/tag-plugins)) are processed by default, to disable: -``` js +```js function lessFn(data, options) { // do something } -lessFn.disableNunjucks = true +lessFn.disableNunjucks = true; -hexo.extend.renderer.register('less', 'css', lessFn); +hexo.extend.renderer.register("less", "css", lessFn); ``` diff --git a/source/ru/api/rendering.md b/source/ru/api/rendering.md index b30735b3b4..a07a22c9ba 100644 --- a/source/ru/api/rendering.md +++ b/source/ru/api/rendering.md @@ -1,14 +1,15 @@ --- title: Рендеринг --- + Существует два метода обработки файлов или строк для рендеринга: асинхронный `hexo.render.render` и синхронный `hexo.render.renderSync`. Нет ничего удивительного в похожести этих методов. Ниже описываются только асинхронные методы. ## Обработка строки При рендеринге строки Hexo необходимо указать, каким обработчиком (`engine`) её обрабатывать. -``` js -hexo.render.render({text: 'example', engine: 'swig'}).then(function(result){ +```js +hexo.render.render({ text: "example", engine: "swig" }).then(function (result) { // ... }); ``` @@ -17,8 +18,8 @@ hexo.render.render({text: 'example', engine: 'swig'}).then(function(result){ При обработке файла не нужно указывать `engine`, потому что Hexo сам обнаружит соответствующий рендер автоматически в зависимости от расширения файла. Конечно, возможно и явно задать обработчик. -``` js -hexo.render.render({path: 'path/to/file.swig'}).then(function(result){ +```js +hexo.render.render({ path: "path/to/file.swig" }).then(function (result) { // ... }); ``` @@ -27,8 +28,8 @@ hexo.render.render({path: 'path/to/file.swig'}).then(function(result){ Можно задать опции в качестве второго аргумента. -``` js -hexo.render.render({text: ''}, {foo: 'foo'}).then(function(result){ +```js +hexo.render.render({ text: "" }, { foo: "foo" }).then(function (result) { // ... }); ``` @@ -37,10 +38,10 @@ hexo.render.render({text: ''}, {foo: 'foo'}).then(function(result){ При окончании обработки Hexo выполнит соответствующие фильтры, заданные в переменной `after_render`. Например, эта функция запустит минификацию JavaScript'а. -``` js -var UglifyJS = require('uglify-js'); +```js +var UglifyJS = require("uglify-js"); -hexo.extend.filter.register('after_render:js', function(str, data){ +hexo.extend.filter.register("after_render:js", function (str, data) { var result = UglifyJS.minify(str); return result.code; }); @@ -50,30 +51,30 @@ hexo.extend.filter.register('after_render:js', function(str, data){ Можно использовать метод `isRenderable` или `isRenderableSync` для проверки, зарегистрирован ли обработчик для типа файла. Только когда соответствующий обработчик был зарегистрирован, будет возвращёно значение `true`. -``` js -hexo.render.isRenderable('layout.swig') // true -hexo.render.isRenderable('image.png') // false +```js +hexo.render.isRenderable("layout.swig"); // true +hexo.render.isRenderable("image.png"); // false ``` ## Определение расширения на выходе Метод `getOutput` получает расширение на выходе обработчика. Если передать необрабатываемый файл, то обработчик вернёт пустую строку. -``` js -hexo.render.getOutput('layout.swig') // html -hexo.render.getOutput('image.png') // ''' +```js +hexo.render.getOutput("layout.swig"); // html +hexo.render.getOutput("image.png"); // ''' ``` ## Disable Nunjucks tags If you are not using a [tag plugin](/docs/tag-plugins) and want to use `{{ }}` or `{% %}` in your post without using content [escaping](/docs/troubleshooting#Escape-Contents), you can disable processing of Nunjucks tag in existing renderer by: -``` js +```js // following example only applies to '.md' file extension // you may need to cover other extensions, e.g. '.markdown', '.mkd', etc -const renderer = hexo.render.renderer.get('md') +const renderer = hexo.render.renderer.get("md"); if (renderer) { - renderer.disableNunjucks = true - hexo.extend.renderer.register('md', 'html', renderer) + renderer.disableNunjucks = true; + hexo.extend.renderer.register("md", "html", renderer); } ``` diff --git a/source/ru/api/router.md b/source/ru/api/router.md index 567221dbf4..2fab87efe3 100644 --- a/source/ru/api/router.md +++ b/source/ru/api/router.md @@ -1,15 +1,16 @@ --- title: Маршрутизатор --- + Маршрутизатор сохраняет все ссылки, используемые на сайте. ## Получение пути Метод `get` возвращает поток [Stream]. Пример для сохранения данных о ссылках в указанное место: -``` js -var data = hexo.route.get('index.html'); -var dest = fs.createWriteStream('somewhere'); +```js +var data = hexo.route.get("index.html"); +var dest = fs.createWriteStream("somewhere"); data.pipe(dest); ``` @@ -18,32 +19,32 @@ data.pipe(dest); Метод `set` принимает строку, [Buffer] или функцию. -``` js +```js // Строка -hexo.route.set('index.html', 'index') +hexo.route.set("index.html", "index"); // Buffer -hexo.route.set('index.html', new Buffer('index')); +hexo.route.set("index.html", new Buffer("index")); // Функция (Запрос) -hexo.route.set('index.html', function(){ - return new Promise(function(resolve, reject){ - resolve('index'); +hexo.route.set("index.html", function () { + return new Promise(function (resolve, reject) { + resolve("index"); }); }); // Функция (Обратный вызов) -hexo.route.set('index.html', function(callback){ - callback(null, 'index'); +hexo.route.set("index.html", function (callback) { + callback(null, "index"); }); ``` Можно также установить логическое значение, был ли изменён путь. Это позволяет увеличить скорость создания файлов, поскольку игнорируются неизменённые ссылки. -``` js -hexo.route.set('index.html', { - data: 'index', - modified: false +```js +hexo.route.set("index.html", { + data: "index", + modified: false, }); // hexo.route.isModified('index.html') => false @@ -51,13 +52,13 @@ hexo.route.set('index.html', { ## Удаление ссылки -``` js -hexo.route.remove('index.html'); +```js +hexo.route.remove("index.html"); ``` ## Получение списка ссылок -``` js +```js hexo.route.list(); ``` @@ -65,8 +66,8 @@ hexo.route.list(); Метод `format` преобразует строку в правильную ссылку. -``` js -hexo.route.format('archives/'); +```js +hexo.route.format("archives/"); // archives/index.html ``` diff --git a/source/ru/api/scaffolds.md b/source/ru/api/scaffolds.md index 47e561ce99..d1740d38e6 100644 --- a/source/ru/api/scaffolds.md +++ b/source/ru/api/scaffolds.md @@ -1,20 +1,21 @@ --- title: Scaffolds --- + ## Получить Scaffold -``` js +```js hexo.scaffold.get(name); ``` ## Установить Scaffold -``` js +```js hexo.scaffold.set(name, content); ``` ## Удалить Scaffold -``` js +```js hexo.scaffold.remove(name); -``` \ No newline at end of file +``` diff --git a/source/ru/api/tag.md b/source/ru/api/tag.md index c461037520..84bd258f06 100644 --- a/source/ru/api/tag.md +++ b/source/ru/api/tag.md @@ -1,14 +1,19 @@ --- title: Тег --- + Тег позволяет легко и быстро вставлять фрагменты в свои посты. ## Краткий обзор -``` js -hexo.extend.tag.register(name, function(args, content){ - // ... -}, options); +```js +hexo.extend.tag.register( + name, + function (args, content) { + // ... + }, + options, +); ``` В функцию тега передаются два аргумента: `args` и `content`. `args` содержит аргументы, передаваемые плагину. `content` оборачивается содержанием с помощью плагина тега. @@ -19,22 +24,22 @@ hexo.extend.tag.register(name, function(args, content){ Use `unregister()` to replace existing [tag plugins](/docs/tag-plugins) with custom functions. -``` js +```js hexo.extend.tag.unregister(name); ``` **Example** -``` js +```js const tagFn = (args, content) => { - content = 'something'; + content = "something"; return content; }; // https://hexo.io/docs/tag-plugins#YouTube -hexo.extend.tag.unregister('youtube'); +hexo.extend.tag.unregister("youtube"); -hexo.extend.tag.register('youtube', tagFn); +hexo.extend.tag.register("youtube", tagFn); ``` ## Опции @@ -53,10 +58,14 @@ hexo.extend.tag.register('youtube', tagFn); Вставка видео с YouTube. -``` js -hexo.extend.tag.register('youtube', function(args){ +```js +hexo.extend.tag.register("youtube", function (args) { var id = args[0]; - return '<div class="video-container"><iframe width="560" height="315" src="http://www.youtube.com/embed/' + id + '" frameborder="0" allowfullscreen></iframe></div>'; + return ( + '<div class="video-container"><iframe width="560" height="315" src="http://www.youtube.com/embed/' + + id + + '" frameborder="0" allowfullscreen></iframe></div>' + ); }); ``` @@ -64,29 +73,43 @@ hexo.extend.tag.register('youtube', function(args){ Вставка цитаты. -``` js -hexo.extend.tag.register('pullquote', function(args, content){ - var className = args.join(' '); - return '<blockquote class="pullquote' + className + '">' + content + '</blockquote>'; -}, {ends: true}); +```js +hexo.extend.tag.register( + "pullquote", + function (args, content) { + var className = args.join(" "); + return ( + '<blockquote class="pullquote' + + className + + '">' + + content + + "</blockquote>" + ); + }, + { ends: true }, +); ``` ### Асинхронная обработка Вставка файла. -``` js -var fs = require('hexo-fs'); -var pathFn = require('path'); - -hexo.extend.tag.register('include_code', function(args){ - var filename = args[0]; - var path = pathFn.join(hexo.source_dir, filename); - - return fs.readFile(path).then(function(content){ - return '<pre><code>' + content + '</code></pre>'; - }); -}, {async: true}); +```js +var fs = require("hexo-fs"); +var pathFn = require("path"); + +hexo.extend.tag.register( + "include_code", + function (args) { + var filename = args[0]; + var path = pathFn.join(hexo.source_dir, filename); + + return fs.readFile(path).then(function (content) { + return "<pre><code>" + content + "</code></pre>"; + }); + }, + { async: true }, +); ``` ## Front-matter and user configuration @@ -95,7 +118,7 @@ Any of the following options is valid: 1. -``` js +```js hexo.extend.tag.register('foo', function (args) { const [firstArg] = args; @@ -120,11 +143,11 @@ hexo.extend.tag.register('foo', function (args) { 2. -``` js index.js -hexo.extend.tag.register('foo', require('./lib/foo')(hexo)); +```js index.js +hexo.extend.tag.register("foo", require("./lib/foo")(hexo)); ``` -``` js lib/foo.js +```js lib/foo.js module.exports = hexo => { return function fooFn(args) { const [firstArg] = args; diff --git a/source/ru/api/themes.md b/source/ru/api/themes.md index 236bc1e6dc..4d82a9f24c 100644 --- a/source/ru/api/themes.md +++ b/source/ru/api/themes.md @@ -1,23 +1,24 @@ --- title: Темы --- + `hexo.theme` является наследником [модулей](box.html) и сохраняет шаблоны. ## Получить визуализацию -``` js +```js hexo.theme.getView(path); ``` ## Установить визуализацию -``` js +```js hexo.theme.setView(path, data); ``` ## Удалить визуализацию -``` js +```js hexo.theme.removeView(path); ``` @@ -25,10 +26,10 @@ hexo.theme.removeView(path); Визуализация использует два метода: `render` и `renderSync`. Они идентичны. Асинхронный `renderSync` является устаревшим, а `render` более новым. Для простоты будет рассмотрен только метод `render`. -``` js -var view = hexo.theme.getView('layout.swig'); +```js +var view = hexo.theme.getView("layout.swig"); -view.render({foo: 1, bar: 2}).then(function(result){ +view.render({ foo: 1, bar: 2 }).then(function (result) { // ... }); ``` diff --git a/source/ru/docs/asset-folders.md b/source/ru/docs/asset-folders.md index 4ea87f2d73..4df6a67b4a 100644 --- a/source/ru/docs/asset-folders.md +++ b/source/ru/docs/asset-folders.md @@ -1,6 +1,7 @@ --- title: Папки с материалами --- + ## Глобальная папка с материалами Материалы, не связанные с постами, такие как изображения, CSS или JavaScript файлы хранятся в папке `source`. Например, если нужно добавить несколько изображений в проект Hexo, то самый простой способ - положить их в исходный каталог изображений `source/images`. Затем можно получить к ним доступ, используя что-то вроде `![](/images/image.jpg)`. @@ -9,7 +10,7 @@ title: Папки с материалами Для пользователей, которые планируют регулярно использовать изображения и/или другие материалы, и для тех, кто предпочитает разделять свои материалы по постам, Hexo обеспечивает возможность организовать управление материалами. Этот немного сложный, но в то же время удобный подход к управлению материалами может быть включён в настройках установкой переменной `post_asset_folder` в `_config.yml` в значение `true`. -``` yaml _config.yml +```yaml _config.yml post_asset_folder: true ``` @@ -25,7 +26,7 @@ post_asset_folder: true {% asset_link slug [title] %} ``` -К примеру, при включённом управление материалами, если поместить в папку с материалами поста изображение `example.jpg`, то ссылка *не заработает* на главной странице, если использовать её по относительному пути `![](example.jpg)` (но в самом посте ссылка будет работать, как и положено). +К примеру, при включённом управление материалами, если поместить в папку с материалами поста изображение `example.jpg`, то ссылка _не заработает_ на главной странице, если использовать её по относительному пути `![](example.jpg)` (но в самом посте ссылка будет работать, как и положено). Правильный путём для ссылки на изображение будет использование синтаксиса плагина тега, а не markdown: @@ -42,10 +43,11 @@ post_asset_folder: true Чтобы включить: -``` yml _config.yml +```yml _config.yml post_asset_folder: true marked: prependRoot: true postAsset: true ``` + После включения изображение материала будет автоматически преобразовано в путь к соответствующей записи. Например, "image.jpg" находится в "/2020/01/02/foo/image.jpg", это означает, что изображение материала "/2020/01/02/foo/" статьи, `![](image.jpg)` будет представлено как `<img src="/2020/01/02/foo/image.jpg">`. diff --git a/source/ru/docs/commands.md b/source/ru/docs/commands.md index dcbdcba1ef..6ed614d7ec 100644 --- a/source/ru/docs/commands.md +++ b/source/ru/docs/commands.md @@ -4,7 +4,7 @@ title: Команды ## init -``` bash +```bash $ hexo init [folder] ``` @@ -17,28 +17,28 @@ $ hexo init [folder] ## new -``` bash +```bash $ hexo new [layout] <title> ``` -Будет создана новая статья. Если макет не был указан, Hexo будет использовать значение `default_layout`, указанное в [_config.yml](configuration.html). Если название содержит пробелы, заключите его в кавычки. +Будет создана новая статья. Если макет не был указан, Hexo будет использовать значение `default_layout`, указанное в [\_config.yml](configuration.html). Если название содержит пробелы, заключите его в кавычки. ## generate -``` bash +```bash $ hexo generate ``` Генерирует статичные файлы. -Параметр | Описание ---- | --- -`-d`, `--deploy` | Опубликовать после генерации -`-w`, `--watch` | Отслеживать изменения файлов +| Параметр | Описание | +| ---------------- | ---------------------------- | +| `-d`, `--deploy` | Опубликовать после генерации | +| `-w`, `--watch` | Отслеживать изменения файлов | ## publish -``` bash +```bash $ hexo publish [layout] <filename> ``` @@ -46,45 +46,45 @@ $ hexo publish [layout] <filename> ## server -``` bash +```bash $ hexo server ``` Запускает локальный сервер. По умолчанию адрес: `http://localhost:4000/`. -Параметр | Описание ---- | --- -`-p`, `--port` | Переназначает стандартный порт -`-s`, `--static` | Обрабатывать только статичные файлы -`-l`, `--log` | Включить журналирование. Переопределяет формат журнала. +| Параметр | Описание | +| ---------------- | ------------------------------------------------------- | +| `-p`, `--port` | Переназначает стандартный порт | +| `-s`, `--static` | Обрабатывать только статичные файлы | +| `-l`, `--log` | Включить журналирование. Переопределяет формат журнала. | ## deploy -``` bash +```bash $ hexo deploy ``` Публикует сайт. -Параметр | Описание ---- | --- -`-g`, `--generate` | Генерировать перед публикацией +| Параметр | Описание | +| ------------------ | ------------------------------ | +| `-g`, `--generate` | Генерировать перед публикацией | ## render -``` bash +```bash $ hexo render <file1> [file2] ... ``` Генерирует файлы. -Параметр | Описание ---- | --- -`-o`, `--output` | Путь вывода +| Параметр | Описание | +| ---------------- | ----------- | +| `-o`, `--output` | Путь вывода | ## migrate -``` bash +```bash $ hexo migrate <type> ``` @@ -92,7 +92,7 @@ $ hexo migrate <type> ## clean -``` bash +```bash $ hexo clean ``` @@ -100,7 +100,7 @@ $ hexo clean ## list -``` bash +```bash $ hexo list <type> ``` @@ -108,7 +108,7 @@ $ hexo list <type> ## version -``` bash +```bash $ hexo version ``` @@ -118,7 +118,7 @@ $ hexo version ### Безопасный режим -``` bash +```bash $ hexo --safe ``` @@ -126,7 +126,7 @@ $ hexo --safe ### Режим отладки -``` bash +```bash $ hexo --debug ``` @@ -134,7 +134,7 @@ $ hexo --debug ### Тихий режим -``` bash +```bash $ hexo --silent ``` @@ -142,7 +142,7 @@ $ hexo --silent ### Альтернативная конфигурация -``` bash +```bash $ hexo --config custom.yml ``` @@ -150,7 +150,7 @@ $ hexo --config custom.yml ### Показать черновики -``` bash +```bash $ hexo --draft ``` @@ -158,7 +158,7 @@ $ hexo --draft ### Изменить рабочую папку -``` bash +```bash $ hexo --cwd /path/to/cwd ``` diff --git a/source/ru/docs/configuration.md b/source/ru/docs/configuration.md index 8465627586..ea042a774e 100644 --- a/source/ru/docs/configuration.md +++ b/source/ru/docs/configuration.md @@ -1,31 +1,32 @@ --- title: Конфигурация --- + Можно изменить настройки в файле `_config.yml`. ### Сайт -Настройки | Описание ---- | --- -`title` | Название сайта -`subtitle` | Подзаголовок сайта -`description` | Описание сайта -`keywords` | Ключевые слова вашего сайта. Поддерживает несколько значений. -`author` | Ваше имя -`language` | Язык сайта. Используйте [2-значный код ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). По умолчанию: `en`. -`timezone` | Временной пояс. Hexo использует настройки компьютера по умолчанию. Список доступных часовых поясов можно найти [здесь](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). Несколько примеров: `America/New_York`, `Japan` и `UTC`. +| Настройки | Описание | +| ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `title` | Название сайта | +| `subtitle` | Подзаголовок сайта | +| `description` | Описание сайта | +| `keywords` | Ключевые слова вашего сайта. Поддерживает несколько значений. | +| `author` | Ваше имя | +| `language` | Язык сайта. Используйте [2-значный код ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). По умолчанию: `en`. | +| `timezone` | Временной пояс. Hexo использует настройки компьютера по умолчанию. Список доступных часовых поясов можно найти [здесь](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). Несколько примеров: `America/New_York`, `Japan` и `UTC`. | ### URL -Параметр | Описание | Умолчание ---- | --- | --- -`url` | URL-адрес сайта, должен начинаться с `http://` или `https://` | -`root` | Корневая папка сайта | `url's pathname` -`permalink` | [Постоянная ссылка](permalinks.html) используются ссылки на статьи | `:year/:month/:day/:title/` -`permalink_defaults` | Значение по умолчанию для каждого сегмента постоянной ссылки | -`pretty_urls` | Переопределите [`permalink`](variables.html) переменную для создания "красивых" URLs ссылок. | -`pretty_urls.trailing_index` | Включает показывание `index.html`, установите значение `false` для удаления. | `true` -`pretty_urls.trailing_html` | Включает показывание `.html`, установите значение `false` для удаления (_не применяется к показу `index.html`_) | `true` +| Параметр | Описание | Умолчание | +| ---------------------------- | --------------------------------------------------------------------------------------------------------------- | --------------------------- | +| `url` | URL-адрес сайта, должен начинаться с `http://` или `https://` | +| `root` | Корневая папка сайта | `url's pathname` | +| `permalink` | [Постоянная ссылка](permalinks.html) используются ссылки на статьи | `:year/:month/:day/:title/` | +| `permalink_defaults` | Значение по умолчанию для каждого сегмента постоянной ссылки | +| `pretty_urls` | Переопределите [`permalink`](variables.html) переменную для создания "красивых" URLs ссылок. | +| `pretty_urls.trailing_index` | Включает показывание `index.html`, установите значение `false` для удаления. | `true` | +| `pretty_urls.trailing_html` | Включает показывание `.html`, установите значение `false` для удаления (_не применяется к показу `index.html`_) | `true` | {% note info Сайт в подпапке %} Если ваш сайт располагается в поддиректории (к примеру `http://example.org/blog`) поменяйте значение `url` на `http://example.org/blog` и установите переменной `root` значение `/blog/`. @@ -33,54 +34,54 @@ title: Конфигурация ### Папки -Параметр | Описание | Умолчание ---- | --- | --- -`source_dir` | Папка с исходниками. Здесь хранится контент | `source` -`public_dir` | Папка публикации. Здесь хранится сгенерированный сайт | `public` -`tag_dir` | Папка с тегами | `tags` -`archive_dir` | Папка с архивами | `archives` -`category_dir` | Папка с категориями | `categories` -`code_dir` | Папка с кодом | `downloads/code` -`i18n_dir` | Папка i18n | `:lang` -`skip_render` | Пути, которые исключены из обработки. Можно использовать [глобальные выражения](https://github.com/micromatch/micromatch#extended-globbing) для определения путей | +| Параметр | Описание | Умолчание | +| -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------- | +| `source_dir` | Папка с исходниками. Здесь хранится контент | `source` | +| `public_dir` | Папка публикации. Здесь хранится сгенерированный сайт | `public` | +| `tag_dir` | Папка с тегами | `tags` | +| `archive_dir` | Папка с архивами | `archives` | +| `category_dir` | Папка с категориями | `categories` | +| `code_dir` | Папка с кодом | `downloads/code` | +| `i18n_dir` | Папка i18n | `:lang` | +| `skip_render` | Пути, которые исключены из обработки. Можно использовать [глобальные выражения](https://github.com/micromatch/micromatch#extended-globbing) для определения путей | ### Написание -Параметр | Описание | Умолчание ---- | --- | --- -`new_post_name` | Имя файла для создания новых постов | `:title.md` -`default_layout` | Макет по умолчанию | `post` -`titlecase` | Преобразовать заголовки в заглавные буквы? | `false` -`external_link` | Открывать внешние ссылки в новой вкладке? | `true` -`external_link.enable` | Открывать внешние ссылки в новой вкладке? | `true` -`external_link.field` | Применяется только ко всему `site` или `post` | `site` -`external_link.exclude` | Исключить имя хоста. Укажите поддомен, когда это применимо, включая `www` | `[]` -`filename_case` | Преобразовать имена файлов в `1` нижний регистр; `2` верхний регистр | `0` -`render_drafts` | Отображать черновики? | `false` -`post_asset_folder` | Включать [папку с материалами](asset-folders.html)? | `false` -`relative_link` | Создание ссылок относительно корневой папки? | `false` -`future` | Отображать будущие посты? | `true` -`syntax_highlighter` | Code block syntax highlight settings, see [Syntax Highlight](/docs/syntax-highlight) section for usage guide | `highlight.js` -`highlight` | Настройки блоков кода, см. [Highlight.js](/docs/syntax-highlight#Highlight-js) раздел для руководства по использованию | -`prismjs` | Настройки блоков кода, см. [PrismJS](/docs/syntax-highlight#PrismJS) раздел для руководства по использованию | +| Параметр | Описание | Умолчание | +| ----------------------- | ---------------------------------------------------------------------------------------------------------------------- | -------------- | +| `new_post_name` | Имя файла для создания новых постов | `:title.md` | +| `default_layout` | Макет по умолчанию | `post` | +| `titlecase` | Преобразовать заголовки в заглавные буквы? | `false` | +| `external_link` | Открывать внешние ссылки в новой вкладке? | `true` | +| `external_link.enable` | Открывать внешние ссылки в новой вкладке? | `true` | +| `external_link.field` | Применяется только ко всему `site` или `post` | `site` | +| `external_link.exclude` | Исключить имя хоста. Укажите поддомен, когда это применимо, включая `www` | `[]` | +| `filename_case` | Преобразовать имена файлов в `1` нижний регистр; `2` верхний регистр | `0` | +| `render_drafts` | Отображать черновики? | `false` | +| `post_asset_folder` | Включать [папку с материалами](asset-folders.html)? | `false` | +| `relative_link` | Создание ссылок относительно корневой папки? | `false` | +| `future` | Отображать будущие посты? | `true` | +| `syntax_highlighter` | Code block syntax highlight settings, see [Syntax Highlight](/docs/syntax-highlight) section for usage guide | `highlight.js` | +| `highlight` | Настройки блоков кода, см. [Highlight.js](/docs/syntax-highlight#Highlight-js) раздел для руководства по использованию | +| `prismjs` | Настройки блоков кода, см. [PrismJS](/docs/syntax-highlight#PrismJS) раздел для руководства по использованию | ### Категории и теги -Параметр | Описание | Умолчание ---- | --- | --- -`default_category` | Категория по умолчанию | `uncategorized` -`category_map` | Карта категорий | -`tag_map` | Карта тегов | +| Параметр | Описание | Умолчание | +| ------------------ | ---------------------- | --------------- | +| `default_category` | Категория по умолчанию | `uncategorized` | +| `category_map` | Карта категорий | +| `tag_map` | Карта тегов | ### Даты / Времени формат Hexo использует [Moment.js](http://momentjs.com/) для работы с датами. -Параметр | Описание | Умолчание ---- | --- | --- -`date_format` | Формат даты | `YYYY-MM-DD` -`time_format` | Формат времени | `HH:mm:ss` -`updated_option` | Значение [`обновлено`](/ru/docs/variables#Переменные-страницы) используется, если оно не указано в front-matter | `mtime` +| Параметр | Описание | Умолчание | +| ---------------- | --------------------------------------------------------------------------------------------------------------- | ------------ | +| `date_format` | Формат даты | `YYYY-MM-DD` | +| `time_format` | Формат времени | `HH:mm:ss` | +| `updated_option` | Значение [`обновлено`](/ru/docs/variables#Переменные-страницы) используется, если оно не указано в front-matter | `mtime` | {% note info updated_option %} `updated_option` управляет значением `updated` если оно не указано в front-matter: @@ -94,18 +95,18 @@ Hexo использует [Moment.js](http://momentjs.com/) для работы ### Разбивка на страницы -Параметр | Описание | Умолчание ---- | --- | --- -`per_page` | Количество постов, отображаемых на странице. `0` отключает разбивку. | `10` -`pagination_dir` | Каталог разбивки | `page` +| Параметр | Описание | Умолчание | +| ---------------- | -------------------------------------------------------------------- | --------- | +| `per_page` | Количество постов, отображаемых на странице. `0` отключает разбивку. | `10` | +| `pagination_dir` | Каталог разбивки | `page` | ### Расширения -Параметр | Описание ---- | --- -`theme` | Имя темы. `false` отключает применение тем -`deploy` | Параметры публикации -`meta_generator` | [Meta generator](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta#Attributes) тегов. `false` отключает ввод тегов. +| Параметр | Описание | +| ---------------- | -------------------------------------------------------------------------------------------------------------------------------- | +| `theme` | Имя темы. `false` отключает применение тем | +| `deploy` | Параметры публикации | +| `meta_generator` | [Meta generator](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta#Attributes) тегов. `false` отключает ввод тегов. | ### Включить/Исключить файлы или каталоги @@ -113,11 +114,11 @@ Hexo использует [Moment.js](http://momentjs.com/) для работы `include` и `exclude` опции применяются только к папке `source/`, тогда как опция `ignore` применяется ко всем папкам. -Параметр | Описание ---- | --- -`include` | По умолчанию Hexo игнорирует скрытые архивы и директории, укажите это значение, чтобы Hexo их обрабатывал -`exclude` | В Hexo будет игнорировать файлы и каталоги, перечисленные в этой переменной -`ignore` | Игнорирует файлы/папки +| Параметр | Описание | +| --------- | --------------------------------------------------------------------------------------------------------- | +| `include` | По умолчанию Hexo игнорирует скрытые архивы и директории, укажите это значение, чтобы Hexo их обрабатывал | +| `exclude` | В Hexo будет игнорировать файлы и каталоги, перечисленные в этой переменной | +| `ignore` | Игнорирует файлы/папки | Примеры: @@ -166,7 +167,7 @@ ignore: Пользовательский файл конфигурации может быть указан при добавлении флага `--config` в команду `hexo` с указанием пути к альтрнативному файу конфигурации YAML или JSON, или даже списку с разделителями-запятыми (без пробелов) нескольких файлов YAML или JSON. -``` bash +```bash # usando 'custom.yml' no lugar de '_config.yml' $ hexo server --config custom.yml @@ -194,7 +195,7 @@ theme: "my-theme" theme_config: bio: "My awesome bio" foo: - bar: 'a' + bar: "a" ``` ```yml @@ -209,11 +210,11 @@ logo: "a-cool-image.png" ```json { - bio: "My awesome bio", - logo: "a-cool-image.png", - foo: { - bar: "a", - baz: "b" + "bio": "My awesome bio", + "logo": "a-cool-image.png", + "foo": { + "bar": "a", + "baz": "b" } } ``` @@ -233,7 +234,7 @@ theme: "my-theme" # _config.my-theme.yml bio: "My awesome bio" foo: - bar: 'a' + bar: "a" ``` ```yml @@ -248,11 +249,11 @@ logo: "a-cool-image.png" ```json { - bio: "My awesome bio", - logo: "a-cool-image.png", - foo: { - bar: "a", - baz: "b" + "bio": "My awesome bio", + "logo": "a-cool-image.png", + "foo": { + "bar": "a", + "baz": "b" } } ``` diff --git a/source/ru/docs/contributing.md b/source/ru/docs/contributing.md index 0ba6bada78..78b5dac957 100644 --- a/source/ru/docs/contributing.md +++ b/source/ru/docs/contributing.md @@ -25,7 +25,7 @@ title: Содействие 1. Создайте форк [hexojs/site] 2. Клонируйте репозиторий на компьютер и установите все зависимости. -``` bash +```bash $ git clone https://github.com/<username>/hexo.git $ cd hexo $ npm install @@ -34,7 +34,7 @@ $ git submodule update --init 3. Создать отдельную ветку. -``` bash +```bash $ git checkout -b new_feature ``` @@ -52,7 +52,7 @@ $ git push origin new_feature - Не изменяйте номер версии в `package.json`. - Ваш запрос могут только принять, когда все тесты пройдут. Не забудьте провести испытания перед отправкой. -``` bash +```bash $ npm test ``` @@ -69,7 +69,7 @@ $ npm test 1. Создайте форк [hexojs/site] 2. Клонируйте репозиторий на компьютер и установите все зависимости. -``` bash +```bash $ npm install hexo-cli -g # If you don't have hexo-cli installed $ git clone https://github.com/<username>/site.git $ cd site @@ -78,7 +78,7 @@ $ npm install 3. Начать редактировать документацию. Вы можете запустить сервер для просмотра изменений. -``` bash +```bash $ hexo server ``` diff --git a/source/ru/docs/data-files.md b/source/ru/docs/data-files.md index 9103027d74..c0e6e88e76 100644 --- a/source/ru/docs/data-files.md +++ b/source/ru/docs/data-files.md @@ -1,11 +1,12 @@ --- title: Файлы с данными --- + Иногда вам может понадобиться использовать данные в шаблонах, которых непосредственно нет в ваших сообщениях, или захотите использовать данные в других местах. Для таких случаев в Hexo 3 введены новые файлы данных. Эта утилита загружает YAML или JSON файлы из исходной папки `source/_data`, поэтому можно использовать их на вашем сайте. Например, добавить `menu.yml` в папку `source/_data`. -``` yaml +```yaml Home: / Gallery: /gallery/ Archives: /archives/ diff --git a/source/ru/docs/front-matter.md b/source/ru/docs/front-matter.md index 29ba3377f5..5a1a285573 100644 --- a/source/ru/docs/front-matter.md +++ b/source/ru/docs/front-matter.md @@ -1,11 +1,12 @@ --- title: Шапка файла --- + Шапка файла это блок в формате YAML или JSON, расположенный в начале файла, который используется для изменения настроек написанного материала. Окончание шапки определяется строкой `---` или `;;;` при написании в формате JSON. **YAML** -``` yaml +```yaml --- title: Hello World date: 2013/7/13 20:46:25 @@ -14,7 +15,7 @@ date: 2013/7/13 20:46:25 **JSON** -``` json +```json "title": "Hello World", "date": "2013/7/13 20:46:25" ;;; @@ -22,25 +23,24 @@ date: 2013/7/13 20:46:25 ### Параметры и значения по умолчанию -Параметр | Описание | Значение по умолчанию ---- | --- | --- -`layout` | Макет | [`config.default_layout`](/ru/docs/configuration#Написание) -`title` | Заголовок | Filename (posts only) -`date` | Дата публикации | Дата создания файла -`updated` | Дата обновления | Дата обновления файла -`comments` | Включение поддержки комментариев в посте | `true` -`tags` | Теги (Недоступно для страниц) | -`categories` | Категории (Не доступно для страниц) | -`permalink` | Переопределяет ссылку по умолчанию. Должна заканчиваться `/` или `.html` | `null` -`excerpt` | Отрывок страницы в виде простого текста. Используйте [этот плагин](/ru/docs/tag-plugins#Отрывок-поста) для оформления текста | -`disableNunjucks` | Отключить отображение тегов Nunjucks `{{ }}`/`{% %}` и [плагины тегов](/ru/docs/tag-plugins) при включении -`lang` | Установите язык для переопределения [автоопределения](/ru/docs/internationalization#Путь) | Берётся из `_config.yml` -`published` | Whether the post should be published | For posts under `_posts`, it is `true`, and for posts under `_draft`, it is `false` - +| Параметр | Описание | Значение по умолчанию | +| ----------------- | ---------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | +| `layout` | Макет | [`config.default_layout`](/ru/docs/configuration#Написание) | +| `title` | Заголовок | Filename (posts only) | +| `date` | Дата публикации | Дата создания файла | +| `updated` | Дата обновления | Дата обновления файла | +| `comments` | Включение поддержки комментариев в посте | `true` | +| `tags` | Теги (Недоступно для страниц) | +| `categories` | Категории (Не доступно для страниц) | +| `permalink` | Переопределяет ссылку по умолчанию. Должна заканчиваться `/` или `.html` | `null` | +| `excerpt` | Отрывок страницы в виде простого текста. Используйте [этот плагин](/ru/docs/tag-plugins#Отрывок-поста) для оформления текста | +| `disableNunjucks` | Отключить отображение тегов Nunjucks `{{ }}`/`{% %}` и [плагины тегов](/ru/docs/tag-plugins) при включении | +| `lang` | Установите язык для переопределения [автоопределения](/ru/docs/internationalization#Путь) | Берётся из `_config.yml` | +| `published` | Whether the post should be published | For posts under `_posts`, it is `true`, and for posts under `_draft`, it is `false` | #### Макет -Умолчания для макета `поста`, берутся в соответствии со значениеми [`параметров`]((https://hexo.io/ru/docs/configuration#Написание)) в файле `_config.yml`. Когда в статье макет отключён (`layout: false`), он не будет обрабатываться с темой. Тем не менее, он все равно будет отображаться любым доступным средством визуализации: если статья написана в Markdown и средстве визуализации Markdown (например, установлен по умолчанию [hexo-renderer-marked](https://github.com/hexojs/hexo-renderer-marked )) , он будет отображён в HTML. +Умолчания для макета `поста`, берутся в соответствии со значениеми [`параметров`](https://hexo.io/ru/docs/configuration#Написание) в файле `_config.yml`. Когда в статье макет отключён (`layout: false`), он не будет обрабатываться с темой. Тем не менее, он все равно будет отображаться любым доступным средством визуализации: если статья написана в Markdown и средстве визуализации Markdown (например, установлен по умолчанию [hexo-renderer-marked](https://github.com/hexojs/hexo-renderer-marked)) , он будет отображён в HTML. [Плагины тегов](/ru/docs/tag-plugins) всегда обрабатываются независимо от макета, если только они не отключены настройкой `disableNunjucks` или [средство визуализации] (/api/renderer#Disable-Nunjucks-tags). @@ -50,12 +50,12 @@ date: 2013/7/13 20:46:25 **Например** -``` yaml +```yaml categories: -- Sports -- Baseball + - Sports + - Baseball tags: -- Injury -- Fight -- Shocking + - Injury + - Fight + - Shocking ``` diff --git a/source/ru/docs/generating.md b/source/ru/docs/generating.md index d8bb7aa2ea..0f97d3fd33 100644 --- a/source/ru/docs/generating.md +++ b/source/ru/docs/generating.md @@ -1,9 +1,10 @@ --- title: Генерация --- + С помощью Hexo генерировать статические файлы просто и легко. -``` bash +```bash hexo generate ``` @@ -11,7 +12,7 @@ hexo generate Hexo может наблюдать за изменениями файлов и сразу генерировать файлы. Hexo сравнивает контрольные суммы файлов SHA1 и записывает файлы только при обнаружении изменений. -``` bash +```bash $ hexo generate --watch ``` @@ -19,7 +20,7 @@ $ hexo generate --watch Для публикации после генерации страниц нужно запустить одну из следующих команд: -``` bash +```bash $ hexo generate --deploy $ hexo deploy --generate ``` diff --git a/source/ru/docs/github-pages.md b/source/ru/docs/github-pages.md index 7de0a02ef9..7730f890d3 100755 --- a/source/ru/docs/github-pages.md +++ b/source/ru/docs/github-pages.md @@ -4,14 +4,14 @@ title: GitHub Pages В этом туториале мы используем [Travis CI](https://travis-ci.com/) для деплоя в Github Pages. [Travis CI](https://travis-ci.com/) бесплатен для репозиториев с открытым исходным кодом, то есть ветка `master` вашего репозитория должна быть публичной. Пожалуйста, перейдите в описание [приватного репозитория](#Private-repository), если вы предпочитаете не открывать свой исходный код, либо откажитесь от загрузки своих файлов на GitHub. -1. Создайте репозиторий с названием <b>*username*.github.io</b>, где `username` — ваше имя пользователя GitHub. Если вы уже загрузили файлы в репозиторий с другим названием, просто переименуйте его. +1. Создайте репозиторий с названием <b>_username_.github.io</b>, где `username` — ваше имя пользователя GitHub. Если вы уже загрузили файлы в репозиторий с другим названием, просто переименуйте его. 2. Загрузите `push` файлы вашей папки Hexo в этот репозиторий. Папка `public/` не должна загружаться по умолчанию, проверьте, что файл `.gitignore` содержит строку `public/`. Структура папки должна быть такой же, как в [этом репозитории](https://github.com/hexojs/hexo-starter), без файла `.gitmodules`. 3. Добавьте [Travis CI](https://github.com/marketplace/travis-ci) в свой аккаунт. 4. Зайдите на страницу [Настроек приложения](https://github.com/settings/installations), сконфигурируйте Travis CI, чтобы оно имело доступ к репозиторию. 5. Вас перенаправят на страницу Travis. 6. В новой вкладке сгенерируйте [новый токен](https://github.com/settings/tokens) с областью видимости **repo**. Запишите значение токена. 7. На странице Travis зайдите в настройки репозитория. В поле **Environment Variables**, вставьте **GH_TOKEN** в качестве имени и токен в качестве значения. Нажмите `Add` для сохранения. -8. Добавьте файл `.travis.yml` в свой репозиторий (рядом с _config.yml & package.json) со следующим контентом: +8. Добавьте файл `.travis.yml` в свой репозиторий (рядом с \_config.yml & package.json) со следующим контентом: ```yml sudo: false @@ -36,14 +36,14 @@ deploy: 9. Как только Travis CI завершит деплой, сгенерированные страницы появятся в ветке `gh-pages` вашего репо. 10. В настройках своего репозитория GitHub перейдите в раздел "GitHub Pages" и измените `Source` на **ветку gh-pages**. -11. Проверьте страницу на *username*.github.io. +11. Проверьте страницу на _username_.github.io. ### Страница проекта Если вы препочитаете страницу проекта на GitHub: -1. Перейдите на страницу своего репо на GitHub. Откройте таб **Settings**. Измените **Repository name**, чтобы ваш блог был доступен на <b>username.github.io/*repository*</b>, **repository** может быть любым словом, как *blog* или *hexo*. -2. Редактируйте файл **_config.yml**, изменив значение `root:` на `/<repository>/` (должно начинаться и заканчиваться косой чертой). +1. Перейдите на страницу своего репо на GitHub. Откройте таб **Settings**. Измените **Repository name**, чтобы ваш блог был доступен на <b>username.github.io/_repository_</b>, **repository** может быть любым словом, как _blog_ или _hexo_. +2. Редактируйте файл **\_config.yml**, изменив значение `root:` на `/<repository>/` (должно начинаться и заканчиваться косой чертой). 3. Закоммитьте и запушьте. ## Приватный репозиторий @@ -51,18 +51,18 @@ deploy: Следующая инструкция адаптирована со страницы [развёртывание одной командой](/docs/one-command-deployment) page. 1. Установите [hexo-deployer-git](https://github.com/hexojs/hexo-deployer-git). -2. Добавьте следующую конфигурацию в **_config.yml**, (удалите существующие строки, если таковые имеются) +2. Добавьте следующую конфигурацию в **\_config.yml**, (удалите существующие строки, если таковые имеются) - ``` yml - deploy: - type: git - repo: https://github.com/<username>/<project> - # example, https://github.com/hexojs/hexojs.github.io - branch: gh-pages - ``` +```yml +deploy: + type: git + repo: https://github.com/<username>/<project> + # example, https://github.com/hexojs/hexojs.github.io + branch: gh-pages +``` 3. Запустите `hexo clean && hexo deploy`. -4. Проверьте веб-страницу по адресу *username*.github.io. +4. Проверьте веб-страницу по адресу _username_.github.io. ## Полезные ссылки diff --git a/source/ru/docs/gitlab-pages.md b/source/ru/docs/gitlab-pages.md index c73a87500d..85ede802f8 100644 --- a/source/ru/docs/gitlab-pages.md +++ b/source/ru/docs/gitlab-pages.md @@ -2,12 +2,12 @@ title: GitLab Pages --- -1. Создайте новый репозиторий под названием <b>*username*.gitlab.io</b>, где `username` — ваше имя пользователя GitLab. Если вы уже загрузили файлы в репозиторий с другим названием, просто переименуйте его. +1. Создайте новый репозиторий под названием <b>_username_.gitlab.io</b>, где `username` — ваше имя пользователя GitLab. Если вы уже загрузили файлы в репозиторий с другим названием, просто переименуйте его. 2. Включите возможность Shared Runners через настройки `Settings -> CI / CD -> Shared Runners`. 3. Запушьте файлы вашей папки Hexo в этот репозиторий. Папка `public/` не должна загружаться по умолчанию, проверьте, что файл `.gitignore` содержит строку `public/`. Структура папки должна быть такой же, как в [этом репозитории](https://gitlab.com/pages/hexo). -4. Добавьте файл `.gitlab-ci.yml` в ваш репозиторий (рядом с _config.yml & package.json) со следующий контентом: +4. Добавьте файл `.gitlab-ci.yml` в ваш репозиторий (рядом с \_config.yml & package.json) со следующий контентом: -``` yml +```yml image: node:10-alpine # use nodejs v10 LTS cache: paths: @@ -27,15 +27,15 @@ pages: - master ``` -5. *username*.gitlab.io должен заработать, как только GitLab CI закончит деплой. +5. _username_.gitlab.io должен заработать, как только GitLab CI закончит деплой. 6. (Опционально) Если вы хотите проверить содержимое папок с материалами (html, css, js и т.д.), они могут быть найдены в разделе [job artifact](https://docs.gitlab.com/ee/user/project/pipelines/job_artifacts.html). ### Страница проекта Если вы препочитаете страницу проекта на GitLab: -1. Перейдите в настройки `Settings -> General -> Advanced -> Change path`. Измените значение на имя так, чтобы сайт был доступен по адресу <b>username.gitlab.io/*name*</b>. Это может быть любое слово, как *blog* или *hexo*. -2. Редактируйте **_config.yml**, изменив значение `root:` с `""` на `"name"`. +1. Перейдите в настройки `Settings -> General -> Advanced -> Change path`. Измените значение на имя так, чтобы сайт был доступен по адресу <b>username.gitlab.io/_name_</b>. Это может быть любое слово, как _blog_ или _hexo_. +2. Редактируйте **\_config.yml**, изменив значение `root:` с `""` на `"name"`. 3. Закоммитьте и запушьте. ## Полезные ссылки diff --git a/source/ru/docs/helpers.md b/source/ru/docs/helpers.md index 4fbf8f5adf..4d6dbc54ac 100644 --- a/source/ru/docs/helpers.md +++ b/source/ru/docs/helpers.md @@ -1,6 +1,7 @@ --- title: Помощники --- + Помощники используются в шаблонах, чтобы быстро вставлять фрагменты. Помощники не могут быть использованы в исходных файлах . ## URL @@ -9,7 +10,7 @@ title: Помощники Возвращает URL-адрес корневого пути с префиксом. Нужно использовать этот помощник вместо `config.root + path`, начиная с Hexo версии 2.7. -``` js +```js <%- url_for(path) %> ``` @@ -17,7 +18,7 @@ title: Помощники Возвращает относительный URL путь от `from` до `to`. -``` js +```js <%- relative_url(from, to) %> ``` @@ -26,13 +27,13 @@ title: Помощники Вставка изображения с Gravatar. Если не указать в параметрах, будет применена опция по умолчанию. Иначе можно установить число, которое будет передаваться в качестве параметра размера изображения, получаемого с Gravatar. Наконец, если установить его ссылкой на объект, он будет преобразован в строку запроса параметров для Gravatar. -``` js +```js <%- gravatar(email, [options]) %> ``` **Примеры:** -``` js +```js <%- gravatar('a@abc.com') %> // https://www.gravatar.com/avatar/b9b00e66c6b8a70f88c73cb6bdb06787 @@ -49,13 +50,13 @@ title: Помощники Загружает CSS-файлы. `path` может быть массивом или строкой. Если путь не начинается с префикса `/` или с любого протокола, то будет начинаться с корневого URL-адреса. Если не добавить `.css` в конце пути, он будет подставлен автоматически. Используйте тип объекта для пользовательских атрибутов. -``` js +```js <%- css(path, ...) %> ``` **Примеры:** -``` js +```js <%- css('style.css') %> // <link rel="stylesheet" href="/style.css"> @@ -75,13 +76,13 @@ title: Помощники Загружает JavaScript файлы. `path` может быть массивом или строкой. Если путь не начинается с префикса `/` или с любого протокола, то будет начинаться с корневого URL-адреса. Если не добавить `.js` в конце пути, он будет подставлен автоматически. Используйте тип объекта для пользовательских атрибутов. -``` js +```js <%- js(path, ...) %> ``` **Примеры:** -``` js +```js <%- js('script.js') %> // <script src="/script.js"></script> @@ -101,19 +102,19 @@ title: Помощники Вставляет ссылку. -``` js +```js <%- link_to(path, [text], [options]) %> ``` -Опции | Описание | Значение по умолчанию ---- | --- | --- -`external` | Открывает ссылку в новой вкладке | false -`class` | Имя класса | -`id` | ID | +| Опции | Описание | Значение по умолчанию | +| ---------- | -------------------------------- | --------------------- | +| `external` | Открывает ссылку в новой вкладке | false | +| `class` | Имя класса | +| `id` | ID | **Примеры:** -``` js +```js <%- link_to('http://www.google.com') %> // <a href="http://www.google.com" title="http://www.google.com">http://www.google.com</a> @@ -128,22 +129,22 @@ title: Помощники Вставка почтовой ссылки. -``` js +```js <%- mail_to(path, [text], [options]) %> ``` -Опция | Описание ---- | --- -`class` | Имя класса -`id` | ID -`subject` | Тема письма -`cc` | Копия -`bcc` | Скрытая копия -`body` | Содержание сообщения +| Опция | Описание | +| --------- | -------------------- | +| `class` | Имя класса | +| `id` | ID | +| `subject` | Тема письма | +| `cc` | Копия | +| `bcc` | Скрытая копия | +| `body` | Содержание сообщения | **Примеры:** -``` js +```js <%- mail_to('a@abc.com') %> // <a href="mailto:a@abc.com" title="a@abc.com">a@abc.com</a> @@ -155,23 +156,23 @@ title: Помощники Вставка изображения. -``` js +```js <%- image_tag(path, [options]) %> ``` -Опция | Описание ---- | --- -`alt` | Альтернативный текст изображения -`class` | Имя класса -`id` | ID -`width` | Ширина изображения -`height` | Высота изображения +| Опция | Описание | +| -------- | -------------------------------- | +| `alt` | Альтернативный текст изображения | +| `class` | Имя класса | +| `id` | ID | +| `width` | Ширина изображения | +| `height` | Высота изображения | ### favicon_tag Вставка иконки сайта (favicon). -``` js +```js <%- favicon_tag(path) %> ``` @@ -179,18 +180,18 @@ title: Помощники Вставка ссылки на канал. -``` js +```js <%- feed_tag(path, [options]) %> ``` -Опции | Описание | Значение по умолчанию ---- | --- | --- -`title` | Имя канала | `config.title` -`type` | Тип канала | +| Опции | Описание | Значение по умолчанию | +| ------- | ---------- | --------------------- | +| `title` | Имя канала | `config.title` | +| `type` | Тип канала | **Examples:** -``` js +```js <%- feed_tag('atom.xml') %> // <link rel="alternate" href="/atom.xml" title="Hexo" type="application/atom+xml"> @@ -208,7 +209,7 @@ title: Помощники Проверить, соответствует ли `path` URL-адресу текущей страницы. Используйте `strict` для обеспечения строгого соответствия. -``` js +```js <%- is_current(path, [strict]) %> ``` @@ -216,7 +217,7 @@ title: Помощники Проверить, является ли текущая страница главной. -``` js +```js <%- is_home() %> ``` @@ -224,7 +225,7 @@ title: Помощники Проверить, является ли текущая страница постом. -``` js +```js <%- is_post() %> ``` @@ -232,7 +233,7 @@ title: Помощники Проверить, является ли текущая страница архивом. -``` js +```js <%- is_archive() %> ``` @@ -240,7 +241,7 @@ title: Помощники Проверить, является ли текущая страница годовым архивом. -``` js +```js <%- is_year() %> ``` @@ -248,7 +249,7 @@ title: Помощники Проверить, является ли текущая страница месячным архивом. -``` js +```js <%- is_month() %> ``` @@ -257,7 +258,7 @@ title: Помощники Проверить, является ли текущая страница страницей категории. Если строка содержит параметр, проверяется, соответствует ли текущая страница заданной категории. -``` js +```js <%- is_category() %> <%- is_category('hobby') %> ``` @@ -266,7 +267,7 @@ title: Помощники Проверить, является ли текущая страница страницей тега. Если строка содержит параметр, проверяется, соответствует ли текущая страница заданному тегу. -``` js +```js <%- is_tag() %> <%- is_tag('hobby') %> ``` @@ -277,7 +278,7 @@ title: Помощники Удаляет префиксы и конечные пробелы из строки. -``` js +```js <%- trim(string) %> ``` @@ -285,13 +286,13 @@ title: Помощники Санирует(sanitizes) все HTML-теги в строку. -``` js +```js <%- strip_html(string) %> ``` **Примеры:** -``` js +```js <%- strip_html('It\'s not <b>important</b> anymore!') %> // It's not important anymore! ``` @@ -300,13 +301,13 @@ title: Помощники Правильно расставляет заглавные буквы в строке заголовка. -``` js +```js <%- titlecase(string) %> ``` **Примеры:** -``` js +```js <%- titlecase('this is an apple') %> # This is an Apple ``` @@ -315,13 +316,13 @@ title: Помощники Преобразует строку с помощью Markdown. -``` js +```js <%- markdown(str) %> ``` **Примеры:** -``` js +```js <%- markdown('make me **strong**') %> // make me <strong>strong</strong> ``` @@ -330,13 +331,13 @@ title: Помощники Обрабатывает строку. -``` js +```js <%- render(str, engine, [options]) %> ``` **Examples:** -``` js +```js <%- render('p(class="example") Test', 'pug'); %> // <p class="example">Test</p> ``` @@ -347,13 +348,13 @@ title: Помощники Переносит строки длиннее указанного в `length` количества символов. `length` равняется 80 по умолчанию. -``` js +```js <%- word_wrap(str, [length]) %> ``` **Примеры:** -``` js +```js <%- word_wrap('Once upon a time', 8) %> // Once upon\n a time ``` @@ -362,13 +363,13 @@ title: Помощники Обрезает текст после определённого в `length` количества символов. По умолчанию `length` 30 символов. -``` js +```js <%- truncate(text, [options]) %> ``` **Примеры:** -``` js +```js <%- truncate('Once upon a time in a world far far away', {length: 17}) %> // Once upon a ti... @@ -383,13 +384,13 @@ title: Помощники Escapes HTML entities in a string. -``` js +```js <%- escape_html(str) %> ``` **Examples:** -``` js +```js <%- escape_html('<p>Hello "world".</p>') %> // <p>Hello "world".</p> ``` @@ -400,26 +401,26 @@ Escapes HTML entities in a string. Загружает другие файлы шаблонов. Можно назначить локальные переменные в `locals`. -``` js +```js <%- partial(layout, [locals], [options]) %> ``` -Опция | Описание | Значение по умолчанию ---- | --- | --- -`cache` | Кэшировать содержимое (Использовать кэш фрагментов.) | `false` -`only` | Строгие локальные переменные. Использовать только указанные в шаблоне переменные `locals`. | `false` +| Опция | Описание | Значение по умолчанию | +| ------- | ------------------------------------------------------------------------------------------ | --------------------- | +| `cache` | Кэшировать содержимое (Использовать кэш фрагментов.) | `false` | +| `only` | Строгие локальные переменные. Использовать только указанные в шаблоне переменные `locals`. | `false` | ### fragment_cache Кэширует содержимое фрагмента. Сохраняет содержимое внутри фрагмента в кэш и при следующем запросе берет значения из него. -``` js +```js <%- fragment_cache(id, fn); ``` **Примеры:** -``` js +```js <%- fragment_cache('header', function(){ return '<header></header>'; }) %> @@ -431,13 +432,13 @@ Escapes HTML entities in a string. Вставляет отформатированную дату. `date` может быть в формате времени Unix, строки ISO, объекта date, или [Moment.js](https://momentjs.com/) объекта. Параметр `format` по умолчанию равен `date_format`. -``` js +```js <%- date(date, [format]) %> ``` **Примеры:** -``` js +```js <%- date(Date.now()) %> // 2013-01-01 @@ -449,28 +450,28 @@ Escapes HTML entities in a string. Вставляет дату в формате XML. `date` может быть в формате времени Unix, строки ISO, объекта date или [Moment.js](https://momentjs.com/) объекта. -``` js +```js <%- date_xml(date) %> ``` **Примеры:** -``` js +```js <%- date_xml(Date.now()) %> // 2013-01-01T00:00:00.000Z ``` ### time -Вставляет отформатированное время. `date` может быть в формате времени Unix, строки ISO, объекта date или [Moment.js](https://momentjs.com/) объекта. Параметр `format` по умолчанию равен `time_format`. +Вставляет отформатированное время. `date` может быть в формате времени Unix, строки ISO, объекта date или [Moment.js](https://momentjs.com/) объекта. Параметр `format` по умолчанию равен `time_format`. -``` js +```js <%- time(date, [format]) %> ``` **Примеры:** -``` js +```js <%- time(Date.now()) %> // 13:05:12 @@ -482,13 +483,13 @@ Escapes HTML entities in a string. Вставляет отформатированные дату и время. `date` может быть в формате времени Unix, строки ISO, объекта date или [Moment.js](https://momentjs.com/) объекта. Параметр `format` по умолчанию равен `date_format + time_format`. -``` js +```js <%- full_date(date, [format]) %> ``` **Примеры:** -``` js +```js <%- full_date(new Date()) %> // Jan 1, 2013 0:00:00 @@ -506,7 +507,7 @@ Inserts relative time from now. `date` can be unix time, ISO string, date object **Examples:** -``` js +```js <%- relative_date(new Date()) %> // a few seconds ago @@ -524,7 +525,7 @@ Inserts time tag. `date` can be unix time, ISO string, date object, or [Moment.j **Examples:** -``` js +```js <%- time_tag(new Date()) %> // <time datetime="2024-01-22T06:35:31.108Z">2024-01-22</time> @@ -542,50 +543,50 @@ Inserts time tag. `date` can be unix time, ISO string, date object, or [Moment.j Вставляет список всех категорий. -``` js +```js <%- list_categories([options]) %> ``` -Опция | Описание | Значение по умолчанию ---- | --- | --- -`orderby` | Упорядочивание категорий | name -`order` | Порядок сортировки. `1`, `asc` для сортировки по возрастанию; `-1`, `desc` для сортировки по убыванию | 1 -`show_count` | Отображать количество постов для каждой категории | true -`style` | Стиль показа списка категорий. `list` отображает категории в неупорядоченном списке. | list -`separator` | Разделитель категорий. (Работает если только стиль `style` не задан как `list`) | , -`depth` | Глубина вложенных категорий для отображения. `0` отображает все категории и подкатегории; `-1` похож на `0` но отображается в плоскости; `1` отображает только разделы верхнего уровня. | 0 -`class` | Имя класса списка категорий. | category -`transform` | Функция, позволяющая изменить отображаемое имя категории. | +| Опция | Описание | Значение по умолчанию | +| ------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- | +| `orderby` | Упорядочивание категорий | name | +| `order` | Порядок сортировки. `1`, `asc` для сортировки по возрастанию; `-1`, `desc` для сортировки по убыванию | 1 | +| `show_count` | Отображать количество постов для каждой категории | true | +| `style` | Стиль показа списка категорий. `list` отображает категории в неупорядоченном списке. | list | +| `separator` | Разделитель категорий. (Работает если только стиль `style` не задан как `list`) | , | +| `depth` | Глубина вложенных категорий для отображения. `0` отображает все категории и подкатегории; `-1` похож на `0` но отображается в плоскости; `1` отображает только разделы верхнего уровня. | 0 | +| `class` | Имя класса списка категорий. | category | +| `transform` | Функция, позволяющая изменить отображаемое имя категории. | ### list_tags Вставка списка всех тегов. -``` js +```js <%- list_tags([options]) %> ``` -Опция | Описание | Значение по умолчанию ---- | --- | --- -`orderby` | Сортировать по категориям | name -`order` | Порядок сортировки. `1`, `asc` по возрастанию; `-1`, `desc` по убыванию | 1 -`show_count` | Отображать количество постов для каждого тега. | true -`style` | Стиль показа списка тегов. `list` отображает категории в неупорядоченном списке. | list -`separator` | Разделитель тегов. (Работает если только стиль `style` не задан как `list`) | , -`class` | Имя класса списка тегов (string) или настройте класс каждого тега (object, см. Ниже). | tag -`transform` | Функция, позволяющая изменить отображаемое имя категории. | -`amount` | Ограничение количества отображаемых тегов (0 = неограниченно) | 0 -`suffix` | Добавьте суффикс к ссылке. | None +| Опция | Описание | Значение по умолчанию | +| ------------ | ------------------------------------------------------------------------------------- | --------------------- | +| `orderby` | Сортировать по категориям | name | +| `order` | Порядок сортировки. `1`, `asc` по возрастанию; `-1`, `desc` по убыванию | 1 | +| `show_count` | Отображать количество постов для каждого тега. | true | +| `style` | Стиль показа списка тегов. `list` отображает категории в неупорядоченном списке. | list | +| `separator` | Разделитель тегов. (Работает если только стиль `style` не задан как `list`) | , | +| `class` | Имя класса списка тегов (string) или настройте класс каждого тега (object, см. Ниже). | tag | +| `transform` | Функция, позволяющая изменить отображаемое имя категории. | +| `amount` | Ограничение количества отображаемых тегов (0 = неограниченно) | 0 | +| `suffix` | Добавьте суффикс к ссылке. | None | Расширенная настройка класса: -Опция | Описание | Значение по умолчанию ---- | --- | --- -`class.ul` | `<ul>` имя класса (только для стиля `list`) | `tag-list` (стиль списка) -`class.li` | `<li>` имя класса (только для стиля `list`) | `tag-list-item` (стиль списка) -`class.a` | `<a>` имя класса | `tag-list-link` (list style) `tag-link` (обычный стиль) -`class.label` | имя класса `<span>`, в котором хранится метка тега (только для обычного стиля, когда задан `class.label`, метка помещается в `<span>`) | `tag-label` (обычный стиль) -`class.count` | имя класса `<span>`, в котором хранится счетчик тегов (только если `show_count` имеет значение `true`) | `tag-list-count` (стиль списка) `tag-count` (обычный стиль) +| Опция | Описание | Значение по умолчанию | +| ------------- | -------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------- | +| `class.ul` | `<ul>` имя класса (только для стиля `list`) | `tag-list` (стиль списка) | +| `class.li` | `<li>` имя класса (только для стиля `list`) | `tag-list-item` (стиль списка) | +| `class.a` | `<a>` имя класса | `tag-list-link` (list style) `tag-link` (обычный стиль) | +| `class.label` | имя класса `<span>`, в котором хранится метка тега (только для обычного стиля, когда задан `class.label`, метка помещается в `<span>`) | `tag-label` (обычный стиль) | +| `class.count` | имя класса `<span>`, в котором хранится счетчик тегов (только если `show_count` имеет значение `true`) | `tag-list-count` (стиль списка) `tag-count` (обычный стиль) | Примеры: @@ -600,60 +601,60 @@ Inserts time tag. `date` can be unix time, ISO string, date object, or [Moment.j Вставка списка архивов. -``` js +```js <%- list_archives([options]) %> ``` -Опция | Описание | Значение по умолчанию ---- | --- | --- -`type` | Тип. Значение может быть год `yearly` или месяц `monthly`. | monthly -`order` | Порядок сортировки. `1`, `asc` по возрастанию; `-1`, `desc` по убывантю | 1 -`show_count` | Отобразить количество сообщений для каждого архива | true -`format` | Формат даты | MMMM YYYY -`style` | Стиль показа списка архивов. `list` отображает категории в неупорядоченном списке. | list -`separator` | Разделитель архивов. (Работает если только стиль `style` не задан как `list`) | , -`class` | Имя класса списка архивов. | archive -`transform` | Функция, позволяющая изменить отображаемое имя архива. | +| Опция | Описание | Значение по умолчанию | +| ------------ | ---------------------------------------------------------------------------------- | --------------------- | +| `type` | Тип. Значение может быть год `yearly` или месяц `monthly`. | monthly | +| `order` | Порядок сортировки. `1`, `asc` по возрастанию; `-1`, `desc` по убывантю | 1 | +| `show_count` | Отобразить количество сообщений для каждого архива | true | +| `format` | Формат даты | MMMM YYYY | +| `style` | Стиль показа списка архивов. `list` отображает категории в неупорядоченном списке. | list | +| `separator` | Разделитель архивов. (Работает если только стиль `style` не задан как `list`) | , | +| `class` | Имя класса списка архивов. | archive | +| `transform` | Функция, позволяющая изменить отображаемое имя архива. | ### list_posts Список постов. -``` js +```js <%- list_posts([options]) %> ``` -Опция | Описание | Значение по умолчанию ---- | --- | --- -`orderby` | Сортировка постов | date -`order` | Порядок сортировки. `1`, `asc` по возрастанию; `-1`, `desc` по убыванию | 1 -`style` | Стиль показа списка постов. `list` отображает категории в неупорядоченном списке. | list -`separator` | Разделитель постов. (Работает если только стиль `style` не задан как `list`) | , -`class` | Имя класса списка постов. | post -`amount` | Ограничени количества отображаемых постов (0 = неограниченно) | 6 -`transform` | Функция, позволяющая изменить отображаемое имя поста. | +| Опция | Описание | Значение по умолчанию | +| ----------- | --------------------------------------------------------------------------------- | --------------------- | +| `orderby` | Сортировка постов | date | +| `order` | Порядок сортировки. `1`, `asc` по возрастанию; `-1`, `desc` по убыванию | 1 | +| `style` | Стиль показа списка постов. `list` отображает категории в неупорядоченном списке. | list | +| `separator` | Разделитель постов. (Работает если только стиль `style` не задан как `list`) | , | +| `class` | Имя класса списка постов. | post | +| `amount` | Ограничени количества отображаемых постов (0 = неограниченно) | 6 | +| `transform` | Функция, позволяющая изменить отображаемое имя поста. | ### tagcloud Облако тегов. -``` js +```js <%- tagcloud([tags], [options]) %> ``` -Опция | Описание | Значение по умолчанию ---- | --- | --- -`min_font` | Минимальный размер шрифта | 10 -`max_font` | Максимальный размер шрифта | 20 -`unit` | Единица измерения размера шрифта | px -`amount` | Общая сумма тегов | 40 -`orderby` | Упорядочить по тегу | name -`order` | Порядок сортировки. `1`, `asc` по возрастанию; `-1`, `desc` по убыванию | 1 -`color` | Цветное облако тегов | false -`start_color` | Стартовый цвет. Можно использовать hex (`#b700ff`), rgba (`rgba(183, 0, 255, 1)`), hsla (`hsla(283, 100%, 50%, 1)`) или [имена цветов]. Эта опция работает только если `color` установлен в `true`. | -`end_color` | Конечный цвет. Можно использовать hex (`#b700ff`), rgba (`rgba(183, 0, 255, 1)`), hsla (`hsla(283, 100%, 50%, 1)`) или [имена цветов]. Эта опция работает только если `color` установлен в `true`. | -`class` | Префикс имени класса тегов -`level` | Количество различных имен классов. Эта опция работает только тогда, когда переменная `class` установлена. | 10 +| Опция | Описание | Значение по умолчанию | +| ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- | +| `min_font` | Минимальный размер шрифта | 10 | +| `max_font` | Максимальный размер шрифта | 20 | +| `unit` | Единица измерения размера шрифта | px | +| `amount` | Общая сумма тегов | 40 | +| `orderby` | Упорядочить по тегу | name | +| `order` | Порядок сортировки. `1`, `asc` по возрастанию; `-1`, `desc` по убыванию | 1 | +| `color` | Цветное облако тегов | false | +| `start_color` | Стартовый цвет. Можно использовать hex (`#b700ff`), rgba (`rgba(183, 0, 255, 1)`), hsla (`hsla(283, 100%, 50%, 1)`) или [имена цветов]. Эта опция работает только если `color` установлен в `true`. | +| `end_color` | Конечный цвет. Можно использовать hex (`#b700ff`), rgba (`rgba(183, 0, 255, 1)`), hsla (`hsla(283, 100%, 50%, 1)`) или [имена цветов]. Эта опция работает только если `color` установлен в `true`. | +| `class` | Префикс имени класса тегов | +| `level` | Количество различных имен классов. Эта опция работает только тогда, когда переменная `class` установлена. | 10 | ## Разное @@ -661,35 +662,35 @@ Inserts time tag. `date` can be unix time, ISO string, date object, or [Moment.j Вставляет нумерацию страниц. -``` js +```js <%- paginator(options) %> ``` -Опция | Описание | Значение по умолчанию ---- | --- | --- -`base` | Базовый URL-адрес | / -`format` | Формат URL-адреса | page/%d/ -`total` | Количество страниц | 1 -`current` | Номер текущей страницы | 0 -`prev_text` | Ссылка на предыдущую страницу. Работает только если `prev_next` имеет значение `true`. | Prev -`next_text` | Ссылка на следующую страницу. Работает только если `prev_next` имеет значение `true`. | Next -`space` | Пространство в тексте | &hellp; -`prev_next` | Отображает ссылки на предыдущую и следующую страницы | true -`end_size` | Количество страниц, отображаемых с начала и конца. | 1 -`mid_size` | Количество страниц, отображаемых от текущей страницы. Текущая страница не включена. | 2 -`show_all` | Отобразить все страницы. Если установлено в `true`, `end_size` и `mid_size` не работают. | false -`escape` | Экранирование HTML-тегов | true +| Опция | Описание | Значение по умолчанию | +| ----------- | ---------------------------------------------------------------------------------------- | --------------------- | +| `base` | Базовый URL-адрес | / | +| `format` | Формат URL-адреса | page/%d/ | +| `total` | Количество страниц | 1 | +| `current` | Номер текущей страницы | 0 | +| `prev_text` | Ссылка на предыдущую страницу. Работает только если `prev_next` имеет значение `true`. | Prev | +| `next_text` | Ссылка на следующую страницу. Работает только если `prev_next` имеет значение `true`. | Next | +| `space` | Пространство в тексте | &hellp; | +| `prev_next` | Отображает ссылки на предыдущую и следующую страницы | true | +| `end_size` | Количество страниц, отображаемых с начала и конца. | 1 | +| `mid_size` | Количество страниц, отображаемых от текущей страницы. Текущая страница не включена. | 2 | +| `show_all` | Отобразить все страницы. Если установлено в `true`, `end_size` и `mid_size` не работают. | false | +| `escape` | Экранирование HTML-тегов | true | **Примеры:** -``` js +```js <%- paginator({ prev_text: '<', next_text: '>' }) %> ``` -``` html +```html <!-- Rendered as --> <a href="/1/"><</a> <a href="/1/">1</a> @@ -698,7 +699,7 @@ Inserts time tag. `date` can be unix time, ISO string, date object, or [Moment.j <a href="/3/">></a> ``` -``` js +```js <%- paginator({ prev_text: '<i class="fa fa-angle-left"></i>', next_text: '<i class="fa fa-angle-right"></i>', @@ -706,7 +707,7 @@ Inserts time tag. `date` can be unix time, ISO string, date object, or [Moment.j }) %> ``` -``` html +```html <!-- Rendered as --> <a href="/1/"><i class="fa fa-angle-left"></i></a> <a href="/1/">1</a> @@ -719,33 +720,33 @@ Inserts time tag. `date` can be unix time, ISO string, date object, or [Moment.j Вставляет форму поиска Google. -``` js +```js <%- search_form(options) %> ``` -Опции | Описание | Значение по умолчанию ---- | --- | --- -`class` | Имя класса формы | search-form -`text` | Подсказка поиска | Search -`button` | Отображать кнопку поиска. Значение может быть логическим или строковым. Если значение — строка, тогда она подставится в текст кнопки. | false +| Опции | Описание | Значение по умолчанию | +| -------- | ------------------------------------------------------------------------------------------------------------------------------------- | --------------------- | +| `class` | Имя класса формы | search-form | +| `text` | Подсказка поиска | Search | +| `button` | Отображать кнопку поиска. Значение может быть логическим или строковым. Если значение — строка, тогда она подставится в текст кнопки. | false | ### number_format Формат чисел. -``` js +```js <%- number_format(number, [options]) %> ``` -Опция | Описание | Значение по умолчанию ---- | --- | --- -`precision` | Точность чисел. Значение можно установить в `false` или неотрицательное целое число. | false -`delimiter` | Разделитель тысяч | , -`separator` | Разделитель дробной части числа от целой. | . +| Опция | Описание | Значение по умолчанию | +| ----------- | ------------------------------------------------------------------------------------ | --------------------- | +| `precision` | Точность чисел. Значение можно установить в `false` или неотрицательное целое число. | false | +| `delimiter` | Разделитель тысяч | , | +| `separator` | Разделитель дробной части числа от целой. | . | **Примеры:** -``` js +```js <%- number_format(12345.67, {precision: 1}) %> // 12,345.68 @@ -766,13 +767,13 @@ Inserts time tag. `date` can be unix time, ISO string, date object, or [Moment.j Добавляет [генерирование тегов](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta). -``` js +```js <%- meta_generator() %> ``` **Примеры:** -``` js +```js <%- meta_generator() %> // <meta name="generator" content="Hexo 4.0.0"> ``` @@ -781,47 +782,47 @@ Inserts time tag. `date` can be unix time, ISO string, date object, or [Moment.j Вставляет график [Open Graph]. -``` js +```js <%- open_graph([options]) %> ``` -Опция | Описание | Значение по умолчанию ---- | --- | --- -`title` | Заголовок страницы (`og:title`) | `page.title` -`type` | Тип страницы (`og:type`) | article(post page)<br>website(non-post page) -`url` | URL-адрес страницы (`og:url`) | `url` -`image` | Обложка страницы (`og:image`) | Все изображения в материалах -`author` | Автор статьи (`og:article:author`) | `config.author` -`date` | Время публикации статьи (`og:article:published_time`) | Время публикации страницы -`updated` | Время изменения статьи (`og:article:modified_time`) | Время изменения страницы -`language` | Язык статьи (`og:locale`) | `page.lang \|\| page.language \|\| config.language` -`site_name` | Имя сайта (`og:site_name`) | `config.title` -`description` | Описание страницы (`og:description`) | Отрывок страницы или первые 200 символов содержимого -`twitter_card` | Карточка Twitter (`twitter:card`) | Краткое изложение -`twitter_id` | Twitter ID (`twitter:creator`) | -`twitter_site` | Сайт Twitter (`twitter:site`) | -`google_plus` | Ссылка на профиль Google+ | -`fb_admins` | Facebook ID администратора | -`fb_app_id` | Facebook ID приложения | +| Опция | Описание | Значение по умолчанию | +| -------------- | ----------------------------------------------------- | ---------------------------------------------------- | +| `title` | Заголовок страницы (`og:title`) | `page.title` | +| `type` | Тип страницы (`og:type`) | article(post page)<br>website(non-post page) | +| `url` | URL-адрес страницы (`og:url`) | `url` | +| `image` | Обложка страницы (`og:image`) | Все изображения в материалах | +| `author` | Автор статьи (`og:article:author`) | `config.author` | +| `date` | Время публикации статьи (`og:article:published_time`) | Время публикации страницы | +| `updated` | Время изменения статьи (`og:article:modified_time`) | Время изменения страницы | +| `language` | Язык статьи (`og:locale`) | `page.lang \|\| page.language \|\| config.language` | +| `site_name` | Имя сайта (`og:site_name`) | `config.title` | +| `description` | Описание страницы (`og:description`) | Отрывок страницы или первые 200 символов содержимого | +| `twitter_card` | Карточка Twitter (`twitter:card`) | Краткое изложение | +| `twitter_id` | Twitter ID (`twitter:creator`) | +| `twitter_site` | Сайт Twitter (`twitter:site`) | +| `google_plus` | Ссылка на профиль Google+ | +| `fb_admins` | Facebook ID администратора | +| `fb_app_id` | Facebook ID приложения | ### toc Анализирует все теги заголовков (H1~н6) на странице и создаёт на их основе оглавление. -``` js +```js <%- toc(str, [options]) %> ``` -Опция | Описание | Значение по умолчанию ---- | --- | --- -`class` | Имя класса | toc -`list_number` | Отображать нумерацию | true -`max_depth` | Максимальная глубина генерации заголовков toc | 6 -`min_depth` | Минимальная глубина генерации заголовков toc | 1 +| Опция | Описание | Значение по умолчанию | +| ------------- | --------------------------------------------- | --------------------- | +| `class` | Имя класса | toc | +| `list_number` | Отображать нумерацию | true | +| `max_depth` | Максимальная глубина генерации заголовков toc | 6 | +| `min_depth` | Минимальная глубина генерации заголовков toc | 1 | **Примеры:** -``` js +```js <%- toc(page.content) %> ``` @@ -837,7 +838,7 @@ Please see below PRs. - https://github.com/hexojs/hexo/pull/4871 - https://github.com/hexojs/hexo-util/pull/269 - https://github.com/hexojs/hexo-renderer-markdown-it/pull/174 -{% endnote %} + {% endnote %} [Имена цветов]: http://www.w3.org/TR/css3-color/#svg-color [Moment.js]: http://momentjs.com/ diff --git a/source/ru/docs/index.md b/source/ru/docs/index.md index 77762032d9..09ba2f3295 100644 --- a/source/ru/docs/index.md +++ b/source/ru/docs/index.md @@ -1,6 +1,7 @@ --- title: Документация --- + Добро пожаловать в документацию Hexo. Если возникнут проблемы при использовании Hexo, попробуйте поискать в [руководстве по решению проблем](troubleshooting.html), поднять вопрос на [GitHub](https://github.com/hexojs/hexo/issues) или завести тему в группе [Google Group](https://groups.google.com/group/hexo). ## Что есть Hexo? @@ -20,7 +21,7 @@ Hexo — это быстрый, простой и мощный фреймвор Если всё это уже есть, поздравляю! Просто установите Hexo с помощью npm: -``` bash +```bash $ npm install -g hexo-cli ``` @@ -55,7 +56,7 @@ nvs также рекомендуется для Mac и Linux, чтобы изб {% endnote %} {% note warn Mac / Linux %} -Если вы столкнулись с ошибкой разрешения `EACCES`обходному при попытке установить Hexo, пожалуйста, следуйте [обходному пути](https://docs.npmjs.com/resolving-eacces-permissions-errors-when-installing-packages-globally ) предоставляенным npmjs; переопределение с помощью root/sudo крайне не рекомендуется. +Если вы столкнулись с ошибкой разрешения `EACCES`обходному при попытке установить Hexo, пожалуйста, следуйте [обходному пути](https://docs.npmjs.com/resolving-eacces-permissions-errors-when-installing-packages-globally) предоставляенным npmjs; переопределение с помощью root/sudo крайне не рекомендуется. {% endnote %} {% note info Linux %} @@ -66,7 +67,7 @@ nvs также рекомендуется для Mac и Linux, чтобы изб После установки всех требуемых программ, можно устанавливать Hexo с помощью npm. -``` bash +```bash $ npm install -g hexo-cli ``` @@ -78,15 +79,15 @@ $ npm install -g hexo-cli Мы настоятельно рекомендуем всегда устанавливать [последнюю версию](https://www.npmjs.com/package/hexo?activeTab=версии) Hexo и [рекомендуемую версию](#Requirements) Node.js , когда это возможно. -Hexo version | Minimum (Node.js version) | Less than (Node.js version) ---- | --- | --- -7.0+ | 14.0.0 | latest -6.2+ | 12.13.0 | latest -6.0+ | 12.13.0 | 18.5.0 -5.0+ | 10.13.0 | 12.0.0 -4.1 - 4.2 | 8.10 | 10.0.0 -4.0 | 8.6 | 8.10.0 -3.3 - 3.9 | 6.9 | 8.0.0 -3.2 - 3.3 | 0.12 | unknown -3.0 - 3.1 | 0.10 or iojs | unknown -0.0.1 - 2.8 | 0.10 | unknown \ No newline at end of file +| Hexo version | Minimum (Node.js version) | Less than (Node.js version) | +| ------------ | ------------------------- | --------------------------- | +| 7.0+ | 14.0.0 | latest | +| 6.2+ | 12.13.0 | latest | +| 6.0+ | 12.13.0 | 18.5.0 | +| 5.0+ | 10.13.0 | 12.0.0 | +| 4.1 - 4.2 | 8.10 | 10.0.0 | +| 4.0 | 8.6 | 8.10.0 | +| 3.3 - 3.9 | 6.9 | 8.0.0 | +| 3.2 - 3.3 | 0.12 | unknown | +| 3.0 - 3.1 | 0.10 or iojs | unknown | +| 0.0.1 - 2.8 | 0.10 | unknown | diff --git a/source/ru/docs/internationalization.md b/source/ru/docs/internationalization.md index 4190cb6051..306b6e20c4 100644 --- a/source/ru/docs/internationalization.md +++ b/source/ru/docs/internationalization.md @@ -1,11 +1,12 @@ --- title: Интернационализация (i18n) --- + [Что такое: i18n](https://ru.wiktionary.org/wiki/i18n) Можно использовать интернационализацию на вашем сайте для поддержки многоязычности. Язык по умолчанию устанавливается путём изменения настройки языка `language` в `_config.yml`. Возможно также установить несколько языков и изменить их порядок по умолчанию. -``` yaml +```yaml language: ru language: @@ -20,9 +21,9 @@ language: ### Шаблоны -Используйте `__` или `_p` в шаблонах помощников, чтобы получить переведённые строки. Первое предназначено для нормального использования, а второе для многострочного использования. Например: +Используйте `__` или `_p` в шаблонах помощников, чтобы получить переведённые строки. Первое предназначено для нормального использования, а второе для многострочного использования. Например: -``` yaml ru.yml +```yaml ru.yml index: title: Главная add: Добавить @@ -32,7 +33,7 @@ index: other: %d видео ``` -``` js +```js <%= __('index.title') %> // Home @@ -44,13 +45,13 @@ index: Вы можете установить язык в шапке страницы или изменить `i18n_dir`, установив значение в `_config.yml` для поддержки автоматического обнаружения в Hexo. -``` yaml +```yaml i18n_dir: :lang ``` Значение по умолчанию `i18n_dir` параметр `:lang` означает, что Hexo будет определять язык в первом сегменте URL-адреса. Например: -``` plain +```plain /index.html => en /archives/index.html => en /zh-tw/index.html => zh-tw diff --git a/source/ru/docs/migration.md b/source/ru/docs/migration.md index 48f56824e5..ca8cf0cd20 100644 --- a/source/ru/docs/migration.md +++ b/source/ru/docs/migration.md @@ -1,17 +1,18 @@ --- title: Миграция --- + ## RSS Прежде нужно установить плагин `hexo-migrator-rss`. -``` bash +```bash $ npm install hexo-migrator-rss --save ``` После установки плагина запустите следующую команду для миграции всех постов в RSS. `source` может быть путём к файлу или URL ссылкой. -``` bash +```bash $ hexo migrate rss <source> ``` @@ -21,7 +22,7 @@ $ hexo migrate rss <source> Измените переменную `new_post_name` в `_config.yml`: -``` yaml +```yaml new_post_name: :year-:month-:day-:title.md ``` @@ -31,7 +32,7 @@ new_post_name: :year-:month-:day-:title.md Измените переменную `new_post_name` в `_config.yml`: -``` yaml +```yaml new_post_name: :year-:month-:day-:title.md ``` @@ -39,7 +40,7 @@ new_post_name: :year-:month-:day-:title.md Сначала установите плагин `hexo-migrator-wordpress`. -``` bash +```bash $ npm install hexo-migrator-wordpress --save ``` @@ -47,7 +48,7 @@ $ npm install hexo-migrator-wordpress --save Выполните: -``` bash +```bash $ hexo migrate wordpress <source> ``` diff --git a/source/ru/docs/one-command-deployment.md b/source/ru/docs/one-command-deployment.md index b343c284f2..2627cc2e3a 100644 --- a/source/ru/docs/one-command-deployment.md +++ b/source/ru/docs/one-command-deployment.md @@ -1,27 +1,28 @@ --- title: Публикация --- + Hexo обеспечивает быстрый и простой способ размещения. Нужна только одна команда, чтобы развернуть свой сайт на сервере. -``` bash +```bash $ hexo deploy ``` Перед первой публикацией сайта нужно изменить некоторые настройки в `_config.yml`. Правильные параметры развёртывания должны иметь поле `type`. Например: -``` yaml +```yaml deploy: type: git ``` Вы можете использовать несколько сервисов размещения. Hexo будет выполнять все в том порядке, какой указан в файле. -``` yaml +```yaml deploy: -- type: git - repo: -- type: heroku - repo: + - type: git + repo: + - type: heroku + repo: ``` Расположение списка дополнительных плагинов для развертывания: [Plugins](https://hexo.io/plugins/). @@ -44,17 +45,17 @@ deploy: message: [message] ``` -Опция | Описание | По умолчанию ---- | --- | --- -`repo` | URL-адрес целевого репозитория | -`branch` | Название ветки. | `gh-pages` (GitHub)<br>`coding-pages` (Coding.net)<br>`master` (другое) -`message` | Конфигурирация сообщения о коммите. | `Site updated: {% raw %}{{ now('YYYY-MM-DD HH:mm:ss') }}{% endraw %}` -`token` | Необязательное значение токена для аутентификации в репозитории. Префикс с `$` для чтения, взятый из переменной среды +| Опция | Описание | По умолчанию | +| --------- | --------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- | +| `repo` | URL-адрес целевого репозитория | +| `branch` | Название ветки. | `gh-pages` (GitHub)<br>`coding-pages` (Coding.net)<br>`master` (другое) | +| `message` | Конфигурирация сообщения о коммите. | `Site updated: {% raw %}{{ now('YYYY-MM-DD HH:mm:ss') }}{% endraw %}` | +| `token` | Необязательное значение токена для аутентификации в репозитории. Префикс с `$` для чтения, взятый из переменной среды | -3. Разместите свой сайт `hexo clean && hexo deploy`. +3. Разместите свой сайт `hexo clean && hexo deploy`. - - Вам будет предложено ввести имя пользователя и пароль целевого репозитория, если вы не аутентифицируетесь с помощью токена или ssh-ключа. - - hexo-deployer-git не хранит ваше имя пользователя и пароль. Используйте [git-credential-cache](https://git-scm.com/docs/git-credential-cache), чтобы временно их хранить. +- Вам будет предложено ввести имя пользователя и пароль целевого репозитория, если вы не аутентифицируетесь с помощью токена или ssh-ключа. +- hexo-deployer-git не хранит ваше имя пользователя и пароль. Используйте [git-credential-cache](https://git-scm.com/docs/git-credential-cache), чтобы временно их хранить. 4. Перейдите в настройки своего репозитория и измените ветвь "Pages" на `gh-pages` (или ветвь, указанную в вашей конфигурации). Развернутый сайт должен быть доступен по ссылке, указанной в параметре "Pages". @@ -62,35 +63,35 @@ deploy: Установите [hexo-deployer-heroku]. -``` bash +```bash $ npm install hexo-deployer-heroku --save ``` Изменение параметров. -``` yaml +```yaml deploy: type: heroku repo: <repository url> message: [message] ``` -Опция | Описание ---- | --- -`repo`, `repository` | Адрес Heroku репозитория -`message` | Изменение описания коммита (По умолчанию: `Site updated: {% raw %}{{ now('YYYY-MM-DD HH:mm:ss') }}{% endraw %}`) +| Опция | Описание | +| -------------------- | ---------------------------------------------------------------------------------------------------------------- | +| `repo`, `repository` | Адрес Heroku репозитория | +| `message` | Изменение описания коммита (По умолчанию: `Site updated: {% raw %}{{ now('YYYY-MM-DD HH:mm:ss') }}{% endraw %}`) | ## Rsync Установите [hexo-deployer-rsync]. -``` bash +```bash $ npm install hexo-deployer-rsync --save ``` Изменение параметров. -``` yaml +```yaml deploy: type: rsync host: <host> @@ -102,15 +103,15 @@ deploy: ignore_errors: [true|false] ``` -Опция | Описание | Умолчание ---- | --- | --- -`host` | Адрес удалённого хоста | -`user` | Имя пользователя | -`root` | Корневой каталог на удалённом хосте | -`port` | Порт | 22 -`delete` | Удаление старых файлов на удаленном хосте | true -`verbose` | Выводить подробные сообщения | true -`ignore_errors` | Игнорировать ошибки | false +| Опция | Описание | Умолчание | +| --------------- | ----------------------------------------- | --------- | +| `host` | Адрес удалённого хоста | +| `user` | Имя пользователя | +| `root` | Корневой каталог на удалённом хосте | +| `port` | Порт | 22 | +| `delete` | Удаление старых файлов на удаленном хосте | true | +| `verbose` | Выводить подробные сообщения | true | +| `ignore_errors` | Игнорировать ошибки | false | ## OpenShift @@ -120,35 +121,35 @@ deploy: Установите [hexo-deployer-openshift]. -``` bash +```bash $ npm install hexo-deployer-openshift --save ``` Изменение параметров. -``` yaml +```yaml deploy: type: openshift repo: <repository url> message: [message] ``` -Опция | Описание ---- | --- -`repo` | Адрес OpenShift репозитория -`message` | Изменение описания коммита (По умолчанию: `Site updated: {% raw %}{{ now('YYYY-MM-DD HH:mm:ss') }}{% endraw %}`) +| Опция | Описание | +| --------- | ---------------------------------------------------------------------------------------------------------------- | +| `repo` | Адрес OpenShift репозитория | +| `message` | Изменение описания коммита (По умолчанию: `Site updated: {% raw %}{{ now('YYYY-MM-DD HH:mm:ss') }}{% endraw %}`) | ## FTPSync Установите [hexo-deployer-ftpsync]. -``` bash +```bash $ npm install hexo-deployer-ftpsync --save ``` Изменение параметров. -``` yaml +```yaml deploy: type: ftpsync host: <host> @@ -160,19 +161,20 @@ deploy: verbose: [true|false] ``` -Опция | Описание | Значение по умолчанию ---- | --- | --- -`host` | Адрес удалённого хоста | -`user` | Имя пользователя | -`pass` | Пароль | -`remote` | Корневой каталог на удалённом хосте | `/` -`port` | Порт | 21 -`clear` | Remove all files and directories from the remote directory before upload | false -`verbose` | Выводить подробные сообщения | false +| Опция | Описание | Значение по умолчанию | +| ------------- | ------------------------------------------------------------------------ | --------------------- | +| `host` | Адрес удалённого хоста | +| `user` | Имя пользователя | +| `pass` | Пароль | +| `remote` | Корневой каталог на удалённом хосте | `/` | +| `port` | Порт | 21 | +| `clear` | Remove all files and directories from the remote directory before upload | false | +| `ignore` | Игнорировать файлы на удалённом хосте | +| `connections` | Количество подключений | 1 | +| `verbose` | Выводить подробные сообщения | false | ## Vercel - [Vercel](https://vercel.com) это облачная платформа, которая позволяет разработчикам размещать веб-сайты и веб-службы Jamstackкоторые мгновенно развертываются, автоматически масштабируются и не требуют контроля, все с нулевой конфигурацией. Они обеспечивают глобальную пограничную сеть, шифрование SSL, сжатие ресурсов, аннулирование кэша и многое другое. Шаг 1: Добавьте сценарий сборки в файл `package.json`: @@ -191,7 +193,7 @@ deploy: Импортируйте проект в Vercel с помощью [Import Flow](https://vercel.com/import/git). Во время импорта вы найдете все соответствующие параметры, предварительно настроенные для вас; однако вы можете изменить любой из этих параметров, список которых можно найти [здесь](https://vercel.com/docs/build-step#build-&-development-settings). -После импорта вашего проекта все последующие изменения в ветви будут создавать [Preview Deployments](https://vercel.com/docs/platform/deployments#preview), и все изменения, внесенные в [Production Branch](https://vercel.com/docs/git-integrations#production-branch ) (обычно "main") приведет к [Production Deployment] (https://vercel.com/docs/platform/deployments#production). +После импорта вашего проекта все последующие изменения в ветви будут создавать [Preview Deployments](https://vercel.com/docs/platform/deployments#preview), и все изменения, внесенные в [Production Branch](https://vercel.com/docs/git-integrations#production-branch) (обычно "main") приведет к [Production Deployment] (https://vercel.com/docs/platform/deployments#production). Кроме того, вы можете нажать кнопку разместить ниже, чтобы создать новый проект: @@ -199,11 +201,10 @@ deploy: ## Bip -[Bip](https://bip.sh ) - это коммерческая услуга хостинга, которая обеспечивает развертывание с нулевым временем простоя, глобальную CDN, SSL, неограниченную пропускную способность и многое другое для статических веб-сайтов. Планы доступны с оплатой по факту (pay as you go), в зависимости от домена. +[Bip](https://bip.sh) - это коммерческая услуга хостинга, которая обеспечивает развертывание с нулевым временем простоя, глобальную CDN, SSL, неограниченную пропускную способность и многое другое для статических веб-сайтов. Планы доступны с оплатой по факту (pay as you go), в зависимости от домена. Начало работы происходит быстро и легко, так как Bip обеспечивает стандартную поддержку Hexo. В этом руководстве предполагается, что у вас уже есть [домен Bip и установленный интерфейс командной строки](https://bip.sh/getstarted). - 1: Инициализируйте каталог вашего проекта ```bash @@ -232,8 +233,8 @@ $ hexo generate —deploy && bip deploy 2. Измените конфигурацию. - ``` yaml - deploy: +```yaml +deploy: - type: rss3 endpoint: https://hub.rss3.io privateKey: 47e18d6c386898b424025cd9db446f779ef24ad33a26c499c87bb3d9372540ba @@ -243,15 +244,15 @@ $ hexo generate —deploy && bip deploy api: key: d693df715d3631e489d6 secret: ee8b74626f12b61c1a4bde3b8c331ad390567c86ba779c9b18561ee92c1cbff0 - ``` - -| Параметры | Описание | -| ----------------- | ---------------------- | -| `endpoint` | Ссылка на RSS3 Hub | -| `privateKey` | Ваш закрытый ключ, 64 байта | -| `ipfs/deploy` | Следует ли развертывать в IPFS | -| `ipfs/gateway` | IPFS API Gateway | -| `ipfs/api/key` | Проверочный контент, связанный со шлюзом IPFS | +``` + +| Параметры | Описание | +| ----------------- | --------------------------------------------- | +| `endpoint` | Ссылка на RSS3 Hub | +| `privateKey` | Ваш закрытый ключ, 64 байта | +| `ipfs/deploy` | Следует ли развертывать в IPFS | +| `ipfs/gateway` | IPFS API Gateway | +| `ipfs/api/key` | Проверочный контент, связанный со шлюзом IPFS | | `ipfs/api/secret` | Проверочный контент, связанный со шлюзом IPFS | 3. Создавайте статические файлы. diff --git a/source/ru/docs/permalinks.md b/source/ru/docs/permalinks.md index cdf29c3237..870c99e940 100644 --- a/source/ru/docs/permalinks.md +++ b/source/ru/docs/permalinks.md @@ -1,84 +1,85 @@ --- title: Постоянные ссылки --- + Вы можете указать формат постоянных ссылок на вашем сайте в файле `_config.yml`. Или в шапке каждого поста. ### Переменные Besides the following variables, you can use any attributes in the permalink except `:path` and `:permalink`. -Переменная | Описание ---- | --- -`:year` | Год публикации поста (4-х значный) -`:month` | Месяц публикации поста (2-х значный) -`:i_month` | Месяц публикации поста (Без ведущего нуля) -`:day` | День публикации поста (2-х значный) -`:i_day` | День публикации поста (Без ведущего нуля) -`:hour` | Published hour of posts (2-digit) -`:minute` | Published minute of posts (2-digit) -`:second` | Published second of posts (2-digit) -`:title` | Имя файла (relative to "source/_posts/" folder) -`:name` | Имя файла -`:post_title` | Post title -`:id` | ID поста (_not persistent across [cache reset](/ru/docs/commands#clean)_) -`:category` | Категории. Если категория поста не указана, возьмётся значение по умолчанию из `default_category`. -`:hash` | SHA1 hash of filename (same as `:title`) and date (12-hexadecimal) +| Переменная | Описание | +| ------------- | -------------------------------------------------------------------------------------------------- | +| `:year` | Год публикации поста (4-х значный) | +| `:month` | Месяц публикации поста (2-х значный) | +| `:i_month` | Месяц публикации поста (Без ведущего нуля) | +| `:day` | День публикации поста (2-х значный) | +| `:i_day` | День публикации поста (Без ведущего нуля) | +| `:hour` | Published hour of posts (2-digit) | +| `:minute` | Published minute of posts (2-digit) | +| `:second` | Published second of posts (2-digit) | +| `:title` | Имя файла (relative to "source/\_posts/" folder) | +| `:name` | Имя файла | +| `:post_title` | Post title | +| `:id` | ID поста (_not persistent across [cache reset](/ru/docs/commands#clean)_) | +| `:category` | Категории. Если категория поста не указана, возьмётся значение по умолчанию из `default_category`. | +| `:hash` | SHA1 hash of filename (same as `:title`) and date (12-hexadecimal) | Можно определить значение по умолчанию для переменной постоянной ссылки, задав значение `permalink_defaults` в конфигурации: -``` yaml +```yaml permalink_defaults: lang: en ``` ### Примеры -``` yaml source/_posts/hello-world.md +```yaml source/_posts/hello-world.md title: Hello World date: 2013-07-14 17:01:34 categories: -- foo -- bar + - foo + - bar ``` -Настройка | Результат ---- | --- -`:year/:month/:day/:title/` | 2013/07/14/hello-world/ -`:year-:month-:day-:title.html` | 2013-07-14-hello-world.html -`:category/:title/` | foo/bar/hello-world/ -`:title-:hash/` | hello-world-a2c8ac003b43/ +| Настройка | Результат | +| ------------------------------- | --------------------------- | +| `:year/:month/:day/:title/` | 2013/07/14/hello-world/ | +| `:year-:month-:day-:title.html` | 2013-07-14-hello-world.html | +| `:category/:title/` | foo/bar/hello-world/ | +| `:title-:hash/` | hello-world-a2c8ac003b43/ | -``` yaml source/_posts/lorem/hello-world.md +```yaml source/_posts/lorem/hello-world.md title: Hello World date: 2013-07-14 17:01:34 categories: -- foo -- bar + - foo + - bar ``` -Настройка | Результат ---- | --- -`:year/:month/:day/:title/` | 2013/07/14/lorem/hello-world/ -`:year/:month/:day/:name/` | 2013/07/14/hello-world/ +| Настройка | Результат | +| --------------------------- | ----------------------------- | +| `:year/:month/:day/:title/` | 2013/07/14/lorem/hello-world/ | +| `:year/:month/:day/:name/` | 2013/07/14/hello-world/ | ### Многоязычность Для создания многоязыкового сайта можно изменить `new_post_name` и `permalink`. Например: -``` yaml +```yaml new_post_name: :lang/:title.md permalink: :lang/:title/ ``` При создании нового поста, он будет сохранен в папке указанного языка: -``` bash +```bash $ hexo new "Hello World" --lang tw # => source/_posts/tw/Hello-World.md ``` ссылка на пост будет: -``` plain +```plain http://localhost:4000/tw/hello-world/ ``` diff --git a/source/ru/docs/plugins.md b/source/ru/docs/plugins.md index 82e9573fc1..0756388e81 100644 --- a/source/ru/docs/plugins.md +++ b/source/ru/docs/plugins.md @@ -1,6 +1,7 @@ --- title: Плагины --- + Hexo имеет мощную систему плагинов, это делает его функции легко расширяемыми, не изменяя код основного модуля. Существует два вида плагинов в Hexo: ### Скрипты @@ -13,15 +14,15 @@ Hexo имеет мощную систему плагинов, это делае Папка должна содержать минимум два файла: один содержит фактический код JavaScript и `package.json`, который описывает назначение плагина и устанавливает его зависимости. -``` plain +```plain . ├── index.js └── package.json ``` -По крайней мере, нужно указать название `name`, версию `version` и параметр `main` в `package.json`. Например: +По крайней мере, нужно указать название `name`, версию `version` и параметр `main` в `package.json`. Например: -``` json package.json +```json package.json { "name": "hexo-my-plugin", "version": "0.0.1", @@ -47,23 +48,21 @@ Hexo имеет мощную систему плагинов, это делае 1. Создайте форк [hexojs/site] 2. Клонируйте репозиторий на компьютер и установите все зависимости. - {% code %} - $ git clone https://github.com/<username>/site.git - $ cd site - $ npm install - {% endcode %} + {% code %} + $ git clone https://github.com/<username>/site.git + $ cd site + $ npm install + {% endcode %} 3. Отредактируйте `source/_data/plugins.yml` добавив свой плагин. Например: - {% code %} - - name: hexo-server - description: Server module for Hexo. - link: https://github.com/hexojs/hexo-server - tags: - - official - - server - - console - {% endcode %} + {% code %} + + - name: hexo-server + description: Server module for Hexo. + link: https://github.com/hexojs/hexo-server + tags: - official - server - console + {% endcode %} 4. Загрузите ветку. 5. Создайте запрос на слияние с описанием изменений. diff --git a/source/ru/docs/server.md b/source/ru/docs/server.md index c67639c01c..9726baa2c7 100644 --- a/source/ru/docs/server.md +++ b/source/ru/docs/server.md @@ -1,23 +1,24 @@ --- title: Сервер --- + ## [hexo-server] С релизом Hexo 3 сервер был отделен от основного модуля. Чтобы начать использовать сервер, нужно установить [hexo-server]. -``` bash +```bash $ npm install hexo-server --save ``` После установки сервера, выполните эту команду для запуска сервера. Ваш сайт будет доступен по адресу `http://localhost:4000` по умолчанию. Когда сервер запущен, Hexo будет отслеживать изменения файлов и автоматически обновлять содержание сайта, поэтому нет нужды вручную перезапускать сервер. -``` bash +```bash $ hexo server ``` Если вы хотите изменить порт или появляется ошибка `EADDRINUSE`, используйте опцию `-p` для задания другого порта. -``` bash +```bash $ hexo server -p 5000 ``` @@ -25,7 +26,7 @@ $ hexo server -p 5000 В статичном режиме, будут обработаны файлы только в общей папке `public`, отслеживание файлов будет отключено. Нужно запустить `hexo generate` перед запуском сервера. Обычно используется перед публикацией. -``` bash +```bash $ hexo server -s ``` @@ -33,8 +34,8 @@ $ hexo server -s Hexo запускает сервер с IP `127.0.0.1` по умолчанию. Это можно изменить в настройках IP по умолчанию. -``` bash +```bash $ hexo server -i 192.168.1.1 ``` -[hexo-server]: https://github.com/hexojs/hexo-server \ No newline at end of file +[hexo-server]: https://github.com/hexojs/hexo-server diff --git a/source/ru/docs/setup.md b/source/ru/docs/setup.md index 3283c1e8ff..4bc83c23b6 100644 --- a/source/ru/docs/setup.md +++ b/source/ru/docs/setup.md @@ -1,9 +1,10 @@ --- title: Установка --- + После установки Hexo, запустите следующие команды в консоли для инициализации Hexo в папке `<folder>`. -``` bash +```bash $ hexo init <folder> $ cd <folder> $ npm install @@ -11,7 +12,7 @@ $ npm install После инициализации папка будет выглядеть так: -``` plain +```plain . ├── _config.yml ├── package.json @@ -22,7 +23,7 @@ $ npm install └── themes ``` -### _config.yml +### \_config.yml Файл [конфигурации](configuration.html) сайта. В нём возможно настроить большинство параметров. @@ -30,7 +31,7 @@ $ npm install Данные приложений. [EJS](https://ejs.co/)-, [Stylus](http://learnboost.github.io/stylus/)- и [Markdown](http://daringfireball.net/projects/markdown/)-обработчики устанавливаются по умолчанию. При желании можно удалить их позже. -``` json package.json +```json package.json { "name": "hexo-site", "version": "0.0.0", diff --git a/source/ru/docs/syntax-highlight.md b/source/ru/docs/syntax-highlight.md index 147c234d3c..2381c1e3d5 100644 --- a/source/ru/docs/syntax-highlight.md +++ b/source/ru/docs/syntax-highlight.md @@ -17,7 +17,7 @@ code snippet code snippet {% endcode %} -``` [language] [title] [url] [link text] [additional options] +```[language] [title] [url] [link text] [additional options] code snippet ``` ```` @@ -35,7 +35,7 @@ highlight: auto_detect: false line_number: true line_threshold: 0 - tab_replace: '' + tab_replace: "" exclude_languages: - example wrap: true @@ -45,7 +45,7 @@ prismjs: preprocess: true line_number: true line_threshold: 0 - tab_replace: '' + tab_replace: "" ``` The YAML above is Hexo's default configuration. @@ -85,7 +85,7 @@ highlight: auto_detect: false line_number: true line_threshold: 0 - tab_replace: ' ' + tab_replace: " " exclude_languages: - example wrap: true @@ -116,18 +116,18 @@ Hexo adds line number by wrapping output inside `<figure>` and `<table>`: ```html <figure class="highlight yaml"> -<table> -<tbody> -<tr> - <td class="gutter"> - <pre><span class="line">1</span><br></pre> - </td> - <td class="code"> - <pre><span class="line"><span class="attr">hello:</span><span class="string">hexo</span></span><br></pre> - </td> -</tr> -</tbody> -</table> + <table> + <tbody> + <tr> + <td class="gutter"> + <pre><span class="line">1</span><br></pre> + </td> + <td class="code"> + <pre><span class="line"><span class="attr">hello:</span><span class="string">hexo</span></span><br></pre> + </td> + </tr> + </tbody> + </table> </figure> ``` @@ -143,7 +143,6 @@ Accepts an optional threshold to only show line numbers as long as the numbers o Replace tabs inside code block with given string. By default it is 2 spaces. - ### exclude_languages (+6.1.0) Only wrap with `<pre><code class="lang"></code></pre>` and will not render all tags(`span`, and `br`) in content if are languages matches this option. @@ -187,7 +186,7 @@ prismjs: preprocess: true line_number: true line_threshold: 0 - tab_replace: '' + tab_replace: "" ``` Prismjs is disabled by default. You should set `highlight.enable` to `false` before enabling prismjs. diff --git a/source/ru/docs/tag-plugins.md b/source/ru/docs/tag-plugins.md index dd0ab7563a..aa33a2b1d5 100644 --- a/source/ru/docs/tag-plugins.md +++ b/source/ru/docs/tag-plugins.md @@ -1,6 +1,7 @@ --- title: Плагины тегов --- + Плагины тегов отличаются от тегов в посте. Они портированы с Octopress и обеспечивают удобный способ, чтобы быстро добавить контент для ваших постов. Although you can write your posts in any formats, but the tag plugins will always be available and syntax remains the same. @@ -83,14 +84,14 @@ code snippet Specify additional options in `option:value` format, e.g. `line_number:false first_line:5`. -Extra Options | Description | Default ---- | --- | --- -`line_number` | Show line number | `true` -`line_threshold` | Only show line numbers as long as the numbers of lines of the code block exceed such threshold. | `0` | -`highlight` | Enable code highlighting | `true` -`first_line` | Specify the first line number | `1` -`mark` | Line highlight specific line(s), each value separated by a comma. Specify number range using a dash<br>Example: `mark:1,4-7,10` will mark line 1, 4 to 7 and 10. | -`wrap` | Wrap the code block in [`<table>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table) | `true` +| Extra Options | Description | Default | +| ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| `line_number` | Show line number | `true` | +| `line_threshold` | Only show line numbers as long as the numbers of lines of the code block exceed such threshold. | `0` | +| `highlight` | Enable code highlighting | `true` | +| `first_line` | Specify the first line number | `1` | +| `mark` | Line highlight specific line(s), each value separated by a comma. Specify number range using a dash<br>Example: `mark:1,4-7,10` will mark line 1, 4 to 7 and 10. | +| `wrap` | Wrap the code block in [`<table>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table) | `true` | ### Примеры @@ -140,7 +141,7 @@ _.compact([0, 1, false, 2, '', 3]); ``` {% codeblock _.compact http://underscorejs.org/#compact Underscore.js %} -_.compact([0, 1, false, 2, '', 3]); +\_.compact([0, 1, false, 2, '', 3]); => [1, 2, 3] {% endcodeblock %} @@ -149,9 +150,9 @@ _.compact([0, 1, false, 2, '', 3]); Тот же блок кода, но использует три обратные кавычки для отделения блока. {% raw %} -``` [language] [title] [url] [link text] +`` [language] [title] [url] [link text] code snippet -``` +`` {% endraw %} ## Цитата @@ -336,32 +337,32 @@ _hexo-renderer-marked 3.1.0+ can (optionally) resolves the post's path of an ima `{% asset_img foo.jpg %}` -``` html -<img src="/2020/01/02/hello/foo.jpg"> +```html +<img src="/2020/01/02/hello/foo.jpg" /> ``` **Custom class** `{% asset_img post-image foo.jpg %}` -``` html -<img src="/2020/01/02/hello/foo.jpg" class="post-image"> +```html +<img src="/2020/01/02/hello/foo.jpg" class="post-image" /> ``` **Display size** `{% asset_img foo.jpg 500 400 %}` -``` html -<img src="/2020/01/02/hello/foo.jpg" width="500" height="400"> +```html +<img src="/2020/01/02/hello/foo.jpg" width="500" height="400" /> ``` **Title & Alt** `{% asset_img logo.svg "lorem ipsum'dolor'" %}` -``` html -<img src="/2020/01/02/hello/foo.jpg" title="lorem ipsum" alt="dolor"> +```html +<img src="/2020/01/02/hello/foo.jpg" title="lorem ipsum" alt="dolor" /> ``` ## URL @@ -376,23 +377,23 @@ Returns a url with the root path prefixed. Output is encoded automatically. **Examples:** -``` yml +```yml _config.yml root: /blog/ # example ``` -``` +``` {% url_for blog index.html %} ``` -``` html +```html <a href="/blog/index.html">blog</a> ``` Relative link, follows `relative_link` option by default e.g. post/page path is '/foo/bar/index.html' -``` yml +```yml _config.yml relative_link: true ``` @@ -401,7 +402,7 @@ relative_link: true {% url_for blog index.html %} ``` -``` html +```html <a href="../../index.html">blog</a> ``` @@ -411,7 +412,7 @@ You could also disable it to output a non-relative link, even when `relative_lin {% url_for blog index.html false %} ``` -``` html +```html <a href="/index.html">blog</a> ``` @@ -425,7 +426,7 @@ Returns a url with the `config.url` prefixed. Output is encoded automatically. **Examples:** -``` yml +```yml _config.yml url: https://example.com/blog # example ``` @@ -434,7 +435,7 @@ url: https://example.com/blog # example {% full_url_for index /a/path %} ``` -``` html +```html <a href="https://example.com/blog/a/path">index</a> ``` diff --git a/source/ru/docs/templates.md b/source/ru/docs/templates.md index a1c4d2209f..14bbf99fcb 100644 --- a/source/ru/docs/templates.md +++ b/source/ru/docs/templates.md @@ -1,60 +1,66 @@ --- title: Шаблоны --- + Шаблон определяет, как страница определённого вида будет выглядеть на вашем сайте. В таблице ниже приведены соответствующие шаблоны для любой страницы. Как минимум, тема должна содержать шаблон `index`. -Шаблон | Страница | Резерв ---- | --- | --- -`index` | Домашняя страница | -`post` | Посты | `index` -`page` | Страницы | `index` -`archive` | Архив | `index` -`category` | Категории архивов | `archive` -`tag` | Архив тегов | `archive` +| Шаблон | Страница | Резерв | +| ---------- | ----------------- | --------- | +| `index` | Домашняя страница | +| `post` | Посты | `index` | +| `page` | Страницы | `index` | +| `archive` | Архив | `index` | +| `category` | Категории архивов | `archive` | +| `tag` | Архив тегов | `archive` | ## Макеты Если страницы имеют схожую структуру, например, когда два шаблона имеют как верхний, так и нижний колонтитулы, тогда можно рассмотреть возможность использования макета `layout` для вынесения этих структурных сходств. Каждый файл разметки должен содержать переменную `body`, для отображения содержимого шаблона. Например: -``` html index.ejs +```html index.ejs index ``` -``` html layout.ejs -<!DOCTYPE html> +```html layout.ejs +<!doctype html> <html> - <body><%- body %></body> + <body> + <%- body %> + </body> </html> ``` сформируется в: -``` html -<!DOCTYPE html> +```html +<!doctype html> <html> - <body>index</body> + <body> + index + </body> </html> ``` По умолчанию макет `layout` используется всеми другими шаблонами. Вы можете указать дополнительные макеты в шапке файла или установить его значение в `false`, чтобы отключить. Также можно построить сложную вложенную структуру включив в верхней части макета другие макеты. + <!-- TODO: Добавить примеры использования --> ## Части Разбивка на части полезна для обмена компонентами между шаблонами. Типичные примеры включают в себя заголовки, нижние колонтитулы, боковые панели. Можно подставить ваш фрагмент в отдельные файлы, чтобы сделать поддержку сайта намного удобнее. Например: -``` html partial/header.ejs +```html partial/header.ejs <h1 id="logo"><%= config.title %></h1> ``` -``` html index.ejs +```html index.ejs <%- partial('partial/header') %> <div id="content">Home page</div> ``` сформируется в: -``` html +```html <h1 id="logo">My Site</h1> <div id="content">Home page</div> ``` @@ -63,18 +69,18 @@ index Вы можете назначать локальные переменные в шаблонах и после использовать в других шаблонах. -``` html partial/header.ejs +```html partial/header.ejs <h1 id="logo"><%= title></h1> ``` -``` html index.ejs +```html index.ejs <%- partial('partial/header', {title: 'Hello World'}) %> <div id="content">Home page</div> ``` сформируется в: -``` html +```html <h1 id="logo">Hello World</h1> <div id="content">Home page</div> ``` @@ -87,7 +93,7 @@ index Кэширование фрагментов лучше всего использовать для заголовков, колонтитулов, боковых панелей или другого статического контента, который вряд ли будет менятся от шаблона к шаблону. Например: -``` js +```js <%- fragment_cache('header', function(){ return '<header></header>'; }); @@ -95,7 +101,7 @@ index Хотя это можно сделать проще, используя части: -``` js +```js <%- partial('header', {}, {cache: true}); ``` diff --git a/source/ru/docs/themes.md b/source/ru/docs/themes.md index c64d9104b6..e8329af01a 100644 --- a/source/ru/docs/themes.md +++ b/source/ru/docs/themes.md @@ -4,7 +4,7 @@ title: Темы Создать тему Hexo легко, надо просто создать новую папку. Чтобы начать использовать темы, измените настройки `theme` в файле сайта `_config`. Тема должна иметь следующую структуру: -``` plain +```plain . ├── _config.yml ├── languages @@ -13,7 +13,7 @@ title: Темы └── source ``` -### _config.yml +### \_config.yml Файл конфигурации темы. Unlike the site's primary configuration file, Изменения не требуют перезагрузки сервера. @@ -25,7 +25,7 @@ title: Темы Папка шаблонов. Эта папка содержит файлы шаблонов темы, которые определяют внешний вид сайта. Hexo использует шаблонизатор [Nunjucks] по умолчанию, но вы легко сможете установить дополнительные плагины, чтобы поддерживать альтернативные системы, такие как [EJS] или [Pug]. Hexo выбирает шаблонизатор на основе расширения файла. Например: -``` plain +```plain layout.ejs - uses EJS layout.njk - uses Nunjucks ``` @@ -49,28 +49,28 @@ Hexo будет сохранять все обработанные файлы в 1. Создайте форк [hexojs/site] 2. Клонируйте репозиторий на компьютер и установите все зависимости. - ``` shell - git clone ttps://github.com/<username>/site.git - cd site - npm install - ``` + ```shell + git clone ttps://github.com/<username>/site.git + cd site + npm install + ``` 3. Отредактируйте `source/_data/themes.yml` и добавьте свою тему. Например: - ```yaml - - name: landscape - description: Новая тема по умолчанию для Hexo. - link: https://github.com/hexojs/hexo-theme-landscape - preview: http://hexo.io/hexo-theme-landscape - tags: - - official - - responsive - - widget - - two_column - - one_column - ``` - -4. Добавьте скриншот темы (с таким же, как и тема, названием) в папку `source/themes/screenshots`. Он должен быть размером 800*500px в формате PNG. + ```yaml + - name: landscape + description: Новая тема по умолчанию для Hexo. + link: https://github.com/hexojs/hexo-theme-landscape + preview: http://hexo.io/hexo-theme-landscape + tags: + - official + - responsive + - widget + - two_column + - one_column + ``` + +4. Добавьте скриншот темы (с таким же, как и тема, названием) в папку `source/themes/screenshots`. Он должен быть размером 800\*500px в формате PNG. 5. Загрузите ветку. 6. Создайте запрос на слияние с описанием изменений. diff --git a/source/ru/docs/troubleshooting.md b/source/ru/docs/troubleshooting.md index 73423afb6d..d71c03489e 100644 --- a/source/ru/docs/troubleshooting.md +++ b/source/ru/docs/troubleshooting.md @@ -1,18 +1,19 @@ --- title: Решение проблем --- + Если вы столкнулись с проблемами при использовании Hexo, на этот случай существует эта страница со списком ответов на часто возникающие вопросы. Если она не помогла, попробуйте поискать решение на [GitHub](https://github.com/hexojs/hexo/issues) или в нашей группе [Google Group](https://groups.google.com/group/hexo). ## Ошибка обработки YAML -``` plain +```plain JS-YAML: incomplete explicit mapping pair; a key node is missed at line 18, column 29: last_updated: Last updated: %s ``` Заключите строку в кавычки, если она содержит двоеточия. -``` plain +```plain JS-YAML: bad indentation of a mapping entry at line 18, column 31: last_updated:"Last updated: %s" ``` @@ -23,13 +24,13 @@ JS-YAML: bad indentation of a mapping entry at line 18, column 31: ## Ошибка EMFILE -``` plain +```plain Error: EMFILE, too many open files ``` Хотя Node.js и использует неблокирующий ввод/вывод, максимальное количество одновременных операций I/O по-прежнему ограничено. Можно встретить ошибку EMFILE при попытке создания большого количества файлов. Попробуйте запустить следующую команду, чтобы увеличить количество синхронных операций ввода-вывода: -``` bash +```bash $ ulimit -n 10000 ``` @@ -37,7 +38,7 @@ $ ulimit -n 10000 If you encounter the following error: -``` bash +```bash $ ulimit -n 10000 ulimit: open files: cannot modify limit: Operation not permitted ``` @@ -48,23 +49,23 @@ To override the limit: 1. Add the following line to "/etc/security/limits.conf": - ``` - * - nofile 10000 +``` +* - nofile 10000 - # '*' applies to all users and '-' set both soft and hard limits - ``` +# '*' applies to all users and '-' set both soft and hard limits +``` - * The above setting may not apply in some cases, ensure "/etc/pam.d/login" and "/etc/pam.d/lightdm" have the following line. (Ignore this step if those files do not exist) +- The above setting may not apply in some cases, ensure "/etc/pam.d/login" and "/etc/pam.d/lightdm" have the following line. (Ignore this step if those files do not exist) - ``` - session required pam_limits.so - ``` +``` +session required pam_limits.so +``` 2. If you are on a [systemd-based](https://en.wikipedia.org/wiki/Systemd#Adoption) distribution, systemd may override "limits.conf". To set the limit in systemd, add the following line in "/etc/systemd/system.conf" and "/etc/systemd/user.conf": - ``` - DefaultLimitNOFILE=10000 - ``` +``` +DefaultLimitNOFILE=10000 +``` 3. Reboot @@ -86,7 +87,7 @@ FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory ## Проблемы с публикацией в Git -``` plain +```plain error: RPC failed; result=22, HTTP code = 403 fatal: 'username.github.io' does not appear to be a git repository @@ -96,20 +97,19 @@ fatal: 'username.github.io' does not appear to be a git repository ## Проблемы с сервером - -``` plain +```plain Error: listen EADDRINUSE ``` Были запущены два сервера Hexo одновременно, или возможно другое приложение использует тот же порт. Попробуйте изменить настройки порта или запустить сервер Hexo с флагом `-p`. -``` bash +```bash $ hexo server -p 5000 ``` ## Проблема установки плагина -``` plain +```plain npm ERR! node-waf configure build ``` @@ -144,13 +144,13 @@ Hexo использует склад [Warehouse] для своей модели Некоторые данные не могут быть обновлены или вновь созданные файлы идентичны последней версии. Очистите кэш и попробуйте снова. -``` bash +```bash $ hexo clean ``` ## Содержимое не найдено -Hexo использует [Nunjucks] для отображения сообщения ([Swig] использовался в предыдущей версии, он использует похожий синтаксис). Содержимое, обёрнутое, в `{{ }}` или `{% %}`, поможет вам разобраться, какая часть вызвала проблемы. You can skip the parsing by wrapping it with the [`raw`](/docs/tag-plugins#Raw) tag plugin, single backtick ```` `{{ }}` ```` or triple backtick. +Hexo использует [Nunjucks] для отображения сообщения ([Swig] использовался в предыдущей версии, он использует похожий синтаксис). Содержимое, обёрнутое, в `{{ }}` или `{% %}`, поможет вам разобраться, какая часть вызвала проблемы. You can skip the parsing by wrapping it with the [`raw`](/docs/tag-plugins#Raw) tag plugin, single backtick `` `{{ }}` `` or triple backtick. Alternatively, Nunjucks tags can be disabled through the renderer's option (if supported), [API](/api/renderer#Disable-Nunjucks-tags) or [front-matter](/docs/front-matter). ``` @@ -169,13 +169,13 @@ Hello {{ world }} Иногда команда `$ hexo server` возвращает ошибку: -``` plain +```plain Error: watch ENOSPC ... ``` Это может быть исправлено путем запуска `$ npm dedupe`, или, если это не поможет, попробуйте выполнить следующие действия в консоли Linux. -``` plain +```plain $ echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p ``` diff --git a/source/ru/docs/variables.md b/source/ru/docs/variables.md index 8e2cd26014..5f43698b3d 100644 --- a/source/ru/docs/variables.md +++ b/source/ru/docs/variables.md @@ -1,17 +1,18 @@ --- title: Переменные --- + ### Глобальные переменные -Переменная | Описание ---- | --- -`site` | Информация о сайте. -`page` | Информация о конкретной странице и переменные в шапке страницы. -`config` | Конфигурация сайта. -`theme` | Конфигурация темы. Наследуется от конфигурации сайта. -`path` | Путь текущей страницы. -`url` | Полная URL ссылка на текущую страницу. -`env` | Переменные среды. +| Переменная | Описание | +| ---------- | --------------------------------------------------------------- | +| `site` | Информация о сайте. | +| `page` | Информация о конкретной странице и переменные в шапке страницы. | +| `config` | Конфигурация сайта. | +| `theme` | Конфигурация темы. Наследуется от конфигурации сайта. | +| `path` | Путь текущей страницы. | +| `url` | Полная URL ссылка на текущую страницу. | +| `env` | Переменные среды. | {% note warn %} Lodash has been removed from global variables since Hexo 5.0.0. [You-Dont-Need-Lodash-Underscore](https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore) might be helpful for your migration. @@ -19,78 +20,78 @@ Lodash has been removed from global variables since Hexo 5.0.0. [You-Dont-Need-L ### Переменные сайта -Переменная | Описание ---- | --- -`site.posts` | Все посты -`site.pages` | Все страницы -`site.categories` | Все категории -`site.tags` | Все теги +| Переменная | Описание | +| ----------------- | ------------- | +| `site.posts` | Все посты | +| `site.pages` | Все страницы | +| `site.categories` | Все категории | +| `site.tags` | Все теги | ### Переменные страницы **Страница (page)** -Переменная | Описание ---- | --- -`page.title` | Название страницы -`page.date` | Дата создания страницы (Объект [Moment.js]) -`page.updated` | Дата последнего обновления (Объект [Moment.js]) -`page.comments` | Включены ли комментарии -`page.layout` | Имя макета -`page.content` | Полностью обработанное содержание страницы -`page.excerpt` | Отрывок страницы -`page.more` | Содержимое страницы без отрывка -`page.source` | Путь к исходному файлу -`page.full_source` | Полный путь к исходному файлу -`page.path` | URL текущей страницы без корневой части адреса. Обычно используется `url_for(page.path)` в теме. -`page.permalink` | Полный URL-адрес страницы -`page.prev` | Предыдущий пост. `null`, если пост первый. -`page.next` | Следующий пост. `null`, если пост последний. -`page.raw` | Исходники страницы -`page.photos` | Фотографии из страницы (Используется в галерее постов) -`page.link` | Внешняя ссылка на статью (Используется в ссылках поста) +| Переменная | Описание | +| ------------------ | ------------------------------------------------------------------------------------------------ | +| `page.title` | Название страницы | +| `page.date` | Дата создания страницы (Объект [Moment.js]) | +| `page.updated` | Дата последнего обновления (Объект [Moment.js]) | +| `page.comments` | Включены ли комментарии | +| `page.layout` | Имя макета | +| `page.content` | Полностью обработанное содержание страницы | +| `page.excerpt` | Отрывок страницы | +| `page.more` | Содержимое страницы без отрывка | +| `page.source` | Путь к исходному файлу | +| `page.full_source` | Полный путь к исходному файлу | +| `page.path` | URL текущей страницы без корневой части адреса. Обычно используется `url_for(page.path)` в теме. | +| `page.permalink` | Полный URL-адрес страницы | +| `page.prev` | Предыдущий пост. `null`, если пост первый. | +| `page.next` | Следующий пост. `null`, если пост последний. | +| `page.raw` | Исходники страницы | +| `page.photos` | Фотографии из страницы (Используется в галерее постов) | +| `page.link` | Внешняя ссылка на статью (Используется в ссылках поста) | **Пост (post)**: такие же переменные, как и у страницы, но добавлены следующие переменные. -Переменные | Описание ---- | --- -`page.published` | `true`, если пост не проект -`page.categories` | Все категории поста -`page.tags` | Все теги поста +| Переменные | Описание | +| ----------------- | --------------------------- | +| `page.published` | `true`, если пост не проект | +| `page.categories` | Все категории поста | +| `page.tags` | Все теги поста | **Главная страница (index)** -Переменная | Описание ---- | --- -`page.per_page` | Количество постов, отображаемых на странице -`page.total` | Общее число постов -`page.current` | Номер текущей страницы -`page.current_url` | URL текущей страницы -`page.posts` | Посты на этой странице ([Data Model]) -`page.prev` | Номер предыдущей страницы. `0`, если текущая страница является первой. -`page.prev_link` | Ссылка на предыдущую страницу. Равна `''`, если текущая страница является первой. -`page.next` | Номер следующей страницы. Равно `0`, если текущая страница является последней. -`page.next_link` | Ссылка на следующую страницу. Равно `''`, если текущая страница является последней. -`page.path` | URL текущей страницы без корневой части адреса. Обычно используется `url_for(page.path)` в теме. +| Переменная | Описание | +| ------------------ | ------------------------------------------------------------------------------------------------ | +| `page.per_page` | Количество постов, отображаемых на странице | +| `page.total` | Общее число постов | +| `page.current` | Номер текущей страницы | +| `page.current_url` | URL текущей страницы | +| `page.posts` | Посты на этой странице ([Data Model]) | +| `page.prev` | Номер предыдущей страницы. `0`, если текущая страница является первой. | +| `page.prev_link` | Ссылка на предыдущую страницу. Равна `''`, если текущая страница является первой. | +| `page.next` | Номер следующей страницы. Равно `0`, если текущая страница является последней. | +| `page.next_link` | Ссылка на следующую страницу. Равно `''`, если текущая страница является последней. | +| `page.path` | URL текущей страницы без корневой части адреса. Обычно используется `url_for(page.path)` в теме. | **Архив (archive):** Такой же, как макет `index`, но добавлены следующие переменные. -Переменная | Описание ---- | --- -`page.archive` | Приравнивается к `true` -`page.year` | Год архива (4-х значное) -`page.month` | Месяц архива (2-х значное без ведущих нулей) +| Переменная | Описание | +| -------------- | -------------------------------------------- | +| `page.archive` | Приравнивается к `true` | +| `page.year` | Год архива (4-х значное) | +| `page.month` | Месяц архива (2-х значное без ведущих нулей) | **Категория (category):** Такая же, как макет `index`, но добавлены следующие переменные. -Переменная | Описание ---- | --- -`page.category` | Имя категории +| Переменная | Описание | +| --------------- | ------------- | +| `page.category` | Имя категории | **Тег (tag):** Такой же, как макет `index`, но добавлены следующие переменные. -Переменная | Описание ---- | --- -`page.tag` | Имя тега +| Переменная | Описание | +| ---------- | -------- | +| `page.tag` | Имя тега | [Moment.js]: http://momentjs.com/ diff --git a/source/ru/docs/writing.md b/source/ru/docs/writing.md index 507452f6d3..f59cb571a9 100644 --- a/source/ru/docs/writing.md +++ b/source/ru/docs/writing.md @@ -1,9 +1,10 @@ --- title: Написание --- + Чтобы создать новый пост, можно выполнить следующую команду: -``` bash +```bash $ hexo new [layout] <title> ``` @@ -13,11 +14,11 @@ $ hexo new [layout] <title> В Hexo есть три макета по умолчанию: `post`, `page` и `draft`. Каждый из них сохраняется по своему пути. Пользовательские макеты сохраняются в папке `source/_posts`. -Макет | Путь ---- | --- -`post` | `source/_posts` -`page` | `source` -`draft` | `source/_drafts` +| Макет | Путь | +| ------- | ---------------- | +| `post` | `source/_posts` | +| `page` | `source` | +| `draft` | `source/_drafts` | {% note tip Отключение макета %} Если вы не хотите, чтобы статья (пост/страница) обрабатывалась с помощью темы, установите `layout: false` в её шапке. Обратитесь к [этому разделу](/ru/docs/front-matter#Макет) для более подробной информации. @@ -27,20 +28,20 @@ $ hexo new [layout] <title> По умолчанию Hexo использует название поста для создания имени. Для изменения имени файла по умолчанию, можно отредактировать настройки, изменив `new_post_name` в `_config.yml`. Например, у значения `:year-:month-:day-:title.md`, будет префикс с именем файлов и датой создания поста. Можно использовать следующие подстановки: -Подстановка | Описание ---- | --- -`:title` | Заголовок поста (строчными буквами с пробелами заменёнными на дефисы) -`:year` | Год создания. Например: `2015` -`:month` | Месяц создания (с ведущим нулём). Например: `04` -`:i_month` | Месяц создания (без ведущего нуля). Например: `4` -`:day` | День создания (с ведущим нулём). Например: `07` -`:i_day` | Месяц создания (без ведущего нуля). Например: `7` +| Подстановка | Описание | +| ----------- | --------------------------------------------------------------------- | +| `:title` | Заголовок поста (строчными буквами с пробелами заменёнными на дефисы) | +| `:year` | Год создания. Например: `2015` | +| `:month` | Месяц создания (с ведущим нулём). Например: `04` | +| `:i_month` | Месяц создания (без ведущего нуля). Например: `4` | +| `:day` | День создания (с ведущим нулём). Например: `07` | +| `:i_day` | Месяц создания (без ведущего нуля). Например: `7` | ### Черновики Ранее упоминалось о специальном макете в Hexo: `draft`. В нём сообщения при создании сохраняются в папку `source/_drafts`. Можно использовать команду `publish`, чтобы переместить черновик в папку `source/_posts`. `publish` похожа на команду `new`. -``` bash +```bash $ hexo publish [layout] <title> ``` @@ -50,17 +51,17 @@ $ hexo publish [layout] <title> При создании сообщения Hexo строит файлы на основе соответствующего файла с каркасом (`scaffolds`). Например: -``` bash +```bash $ hexo new photo "My Gallery" ``` Когда выполнится эта команда, Hexo постарается найти `photo.md` в папке `scaffolds` и создать пост на его основе. Эти подстановочные части доступны в заготовках: -Подстановка | Описание ---- | --- -`layout` | Макет -`title` | Заголовок -`date` | Дата создания файла +| Подстановка | Описание | +| ----------- | ------------------- | +| `layout` | Макет | +| `title` | Заголовок | +| `date` | Дата создания файла | ### Поддерживаемые форматы diff --git a/source/th/api/box.md b/source/th/api/box.md index e7955c087f..ea773023c2 100644 --- a/source/th/api/box.md +++ b/source/th/api/box.md @@ -1,19 +1,20 @@ --- title: Box --- + box เป็น container ที่ใช้มาจัดการไฟล์ภายใน folder เฉพาะ Hexo ใช้ box ที่แตกต่างกันสองตัว ซึ้งก็คือ `hexo.source` และ `hexo.theme` ตัวแรกใช้มาจัดการ folder `source` และตัวท่ีสองใช้มาจัดการ folder `theme` ## Files Loading -box สนับสนุนวิธีการโหลดไฟล์สองวิธี ซึ้งก็คือ `process` และ `watch` วิธีตัว `process` จะโหลดไฟล์ทั้งหมดใน folder ส่วนวิธีตัว `watch` +box สนับสนุนวิธีการโหลดไฟล์สองวิธี ซึ้งก็คือ `process` และ `watch` วิธีตัว `process` จะโหลดไฟล์ทั้งหมดใน folder ส่วนวิธีตัว `watch` นอกจากจะมีการกระทำที่เหมือนวิธีตัว `process` แล้วแถมยังเฝ้าดูการเปลี่ยนแปลงของไฟล์ที่อยู่ใน folder นั้นด้วย -``` js -box.process().then(function(){ +```js +box.process().then(function () { // ... }); -box.watch().then(function(){ +box.watch().then(function () { // You can call box.unwatch() later to stop watching. }); ``` @@ -22,7 +23,7 @@ box.watch().then(function(){ box สนับสนุนวิธีหลายอย่างสำหรับ path matching คุณสามารถใช้ regExp function หรือ Express-style pattern string เวลาทำเรื่อง path mathching -``` plain +```plain posts/:id => posts/89 posts/*path => posts/2015/title ``` @@ -31,32 +32,32 @@ posts/*path => posts/2015/title ## Processors -processor เป็น element จำเป็นสำหรับ box และใช้มาจัดการไฟล์ คุณสามารถใช้ path matching ที่กล่าวข้างบนมาจำกัดขอบแขดไฟล์ที่อยากจัดการจริงๆ คุณลงทะเบียน processor ตัวใหม่ได้ด้วยวิธี `addProcessor` +processor เป็น element จำเป็นสำหรับ box และใช้มาจัดการไฟล์ คุณสามารถใช้ path matching ที่กล่าวข้างบนมาจำกัดขอบแขดไฟล์ที่อยากจัดการจริงๆ คุณลงทะเบียน processor ตัวใหม่ได้ด้วยวิธี `addProcessor` -``` js -box.addProcessor('posts/:id', function(file){ +```js +box.addProcessor("posts/:id", function (file) { // }); ``` box ส่งเนื้อหาของไฟล์ที่ถูกคัดเลือกไปให้ processor ข้อมูลที่เกี่ยวกับปฎิบัติการนี้จะอ่านได้จาก `file` ที่เป็น argument ของ callback ได้ -Attribute | Description ---- | --- -`source` | Full path of the file -`path` | Relative path to the box of the file -`type` | File type. The value can be `create`, `update`, `skip`, `delete`. -`params` | The information from path matching. +| Attribute | Description | +| --------- | ----------------------------------------------------------------- | +| `source` | Full path of the file | +| `path` | Relative path to the box of the file | +| `type` | File type. The value can be `create`, `update`, `skip`, `delete`. | +| `params` | The information from path matching. | box ยังสนับสนุนวิธีหลายวิธีที่ให้ความสะดวกว่าคุณไม่ต้องทำ IO ของไฟล์ด้วยตนเอง -Method | Description ---- | --- -`read` | Read a file -`readSync` | Read a file synchronously -`stat` | Read the status of a file -`statSync` | Read the status of a file synchronously -`render` | Render a file -`renderSync` | Render a file synchronously +| Method | Description | +| ------------ | --------------------------------------- | +| `read` | Read a file | +| `readSync` | Read a file synchronously | +| `stat` | Read the status of a file | +| `statSync` | Read the status of a file synchronously | +| `render` | Render a file | +| `renderSync` | Render a file synchronously | [util.Pattern]: https://github.com/hexojs/hexo-util#patternrule diff --git a/source/th/api/console.md b/source/th/api/console.md index 1880f65ea4..c8970fbabf 100644 --- a/source/th/api/console.md +++ b/source/th/api/console.md @@ -1,23 +1,24 @@ --- title: Console --- + console เป็นสะพานระหว่าง Hexo และผู้ใช้ของมัน และ console บันทึกและอธิบายคำสั่ง console ที่มีอยู่ ## Synopsis -``` js -hexo.extend.console.register(name, desc, options, function(args){ +```js +hexo.extend.console.register(name, desc, options, function (args) { // ... }); ``` -Argument | Description ---- | --- -`name` | Name -`desc` | Description -`options`| Options +| Argument | Description | +| --------- | ----------- | +| `name` | Name | +| `desc` | Description | +| `options` | Options | - `args` เป็น argument ที่ส่งเข้า function และเป็น argument ท่ีผู้ใช้พิมพ์ลงเข้า Terminal มันจะถูกวิเคราะห์โดย [Minimist] +`args` เป็น argument ที่ส่งเข้า function และเป็น argument ท่ีผู้ใช้พิมพ์ลงเข้า Terminal มันจะถูกวิเคราะห์โดย [Minimist] ## Options @@ -25,8 +26,10 @@ Argument | Description วิธีการใช้งานของคำสั่ง console ยกตัวอย่างเช่น -``` js -{usage: '[layout] <title>'} +```js +{ + usage: "[layout] <title>"; +} // hexo new [layout] <title> ``` @@ -34,12 +37,12 @@ Argument | Description คำอธิบายทุก argument ของคำสั่ง console ยกตัวอย่างเช่น -``` js +```js { arguments: [ - {name: 'layout', desc: 'Post layout'}, - {name: 'title', desc: 'Post title'} - ] + { name: "layout", desc: "Post layout" }, + { name: "title", desc: "Post title" }, + ]; } ``` @@ -47,11 +50,9 @@ Argument | Description คำอธิบายทุกตัวเลือกของคำสั่ง console ยกตัวอย่างเช่น -``` js +```js { - options: [ - {name: '-r, --replace', desc: 'Replace existing files'} - ] + options: [{ name: "-r, --replace", desc: "Replace existing files" }]; } ``` @@ -61,10 +62,14 @@ Argument | Description ## Example -``` js -hexo.extend.console.register('config', 'Display configuration', function(args){ - console.log(hexo.config); -}); +```js +hexo.extend.console.register( + "config", + "Display configuration", + function (args) { + console.log(hexo.config); + }, +); ``` [Minimist]: https://github.com/substack/minimist diff --git a/source/th/api/deployer.md b/source/th/api/deployer.md index 3a15ea9d89..6973c035f7 100644 --- a/source/th/api/deployer.md +++ b/source/th/api/deployer.md @@ -1,14 +1,15 @@ --- title: Deployer --- + deployer เป็นตัวช่วยให้ผู้ใช้ deploy เว็บไซต์ไปถึง remote server โดยไม่ต้องใช้คำสั่งซับซ้อน ## Synopsis -``` js -hexo.extend.deployer.register(name, function(args){ +```js +hexo.extend.deployer.register(name, function (args) { // ... }); ``` -`args` เป็น argument ท่ีจะส่งเข้า function ในไฟล์ `_config.yml` มีค่า `deploy` และคำสั่งท่ีผู้ใช้ต้องการพิมพ์ลงเข้า terminal +`args` เป็น argument ท่ีจะส่งเข้า function ในไฟล์ `_config.yml` มีค่า `deploy` และคำสั่งท่ีผู้ใช้ต้องการพิมพ์ลงเข้า terminal diff --git a/source/th/api/events.md b/source/th/api/events.md index 68208acf1e..08c7d53f65 100644 --- a/source/th/api/events.md +++ b/source/th/api/events.md @@ -2,7 +2,7 @@ title: Events --- -hexo สืบทอดจาก [EventEmitter] มันใช้วิธี `on` มาคอยฟัง event ที่ hexo +hexo สืบทอดจาก [EventEmitter] มันใช้วิธี `on` มาคอยฟัง event ที่ hexo ส่งออกไป ### deployBefore @@ -29,25 +29,25 @@ hexo สืบทอดจาก [EventEmitter] มันใช้วิธี ส่งออกไปหลังการสร้างโพสต์ใหม่ event นี้ส่ง data โพสต์กลับ -``` js -hexo.on('new', function(post){ +```js +hexo.on("new", function (post) { // }); ``` -Data | Description ---- | --- -`post.path` | Full path of the post file -`post.content` | Content of the post file +| Data | Description | +| -------------- | -------------------------- | +| `post.path` | Full path of the post file | +| `post.content` | Content of the post file | ### processBefore -ส่งออกไปก่อนการเกิดขึ้นของ processing event นี้ส่งกลับ path ท่ีบ่งบอก root +ส่งออกไปก่อนการเกิดขึ้นของ processing event นี้ส่งกลับ path ท่ีบ่งบอก root directory ของ box ### processAfter -ส่งออกไปหลังการจบลงของ processing event นี้ส่งกลับ path ท่ีบ่งบอก root directory ของ box +ส่งออกไปหลังการจบลงของ processing event นี้ส่งกลับ path ท่ีบ่งบอก root directory ของ box ### ready diff --git a/source/th/api/filter.md b/source/th/api/filter.md index 638ea9494c..7556c9390b 100644 --- a/source/th/api/filter.md +++ b/source/th/api/filter.md @@ -6,7 +6,7 @@ filter ใช้มาเป็นการแก้ไขข้อมูลเ ## Synopsis -``` js +```js hexo.extend.filter.register(type, function() { // User configuration const { config } = this; @@ -19,74 +19,73 @@ hexo.extend.filter.register(type, function() { }, priority); ``` -ผู้ใช้สามารถตั้งค่า `priority` ได้ ค่าของ `priority` ยิ่งต่ำหมายถึงว่าจะ execute ยิ่งก่อนตัวอื่น ส่วนค่า default ของ `priority` คือ 10. +ผู้ใช้สามารถตั้งค่า `priority` ได้ ค่าของ `priority` ยิ่งต่ำหมายถึงว่าจะ execute ยิ่งก่อนตัวอื่น ส่วนค่า default ของ `priority` คือ 10. ## Execute Filters -``` js +```js hexo.extend.filter.exec(type, data, options); hexo.extend.filter.execSync(type, data, options); ``` -Option | Description ---- | --- -`context` | Context -`args` | Arguments. This must be an array. +| Option | Description | +| --------- | --------------------------------- | +| `context` | Context | +| `args` | Arguments. This must be an array. | -argument ตัวแรกคือ `data` การแก้ไขค่าของ`data` จะเป็นการส่ง `data` เข้า filter และส่งค่าใหม่กลับมา ถ้าไม่มีข้อมูลส่งกลับมา ค่าของ `data` จะคงอยู่เหมือนเดิม ผู้ใช้สามารถใช้ `args` มาชี้ถึง argument อื่นๆใน filter ยกตัวอย่างเช่น: +argument ตัวแรกคือ `data` การแก้ไขค่าของ`data` จะเป็นการส่ง `data` เข้า filter และส่งค่าใหม่กลับมา ถ้าไม่มีข้อมูลส่งกลับมา ค่าของ `data` จะคงอยู่เหมือนเดิม ผู้ใช้สามารถใช้ `args` มาชี้ถึง argument อื่นๆใน filter ยกตัวอย่างเช่น: - -``` js -hexo.extend.filter.register('test', function(data, arg1, arg2){ +```js +hexo.extend.filter.register("test", function (data, arg1, arg2) { // data === 'some data' // arg1 === 'foo' // arg2 === 'bar' - return 'something'; + return "something"; }); -hexo.extend.filter.register('test', function(data, arg1, arg2){ +hexo.extend.filter.register("test", function (data, arg1, arg2) { // data === 'something' }); -hexo.extend.filter.exec('test', 'some data', { - args: ['foo', 'bar'] +hexo.extend.filter.exec("test", "some data", { + args: ["foo", "bar"], }); ``` ผู้ใช้สามารถใช้วิธีต่อไปเพื่อ execute filter: -``` js +```js hexo.execFilter(type, data, options); hexo.execFilterSync(type, data, options); ``` ## Unregister Filters -``` js +```js hexo.extend.filter.unregister(type, filter); ``` **Example** -``` js +```js // Unregister a filter which is registered with named function const filterFn = (data) => { - data = 'something'; + data = "something"; return data; }; -hexo.extend.filter.register('example', filterFn); +hexo.extend.filter.register("example", filterFn); -hexo.extend.filter.unregister('example', filterFn); +hexo.extend.filter.unregister("example", filterFn); ``` -``` js +```js // Unregister a filter which is registered with commonjs module -hexo.extend.filter.register('example', require('path/to/filter')); +hexo.extend.filter.register("example", require("path/to/filter")); -hexo.extend.filter.unregister('example', require('path/to/filter')); +hexo.extend.filter.unregister("example", require("path/to/filter")); ``` ## Filter List @@ -95,12 +94,12 @@ hexo.extend.filter.unregister('example', require('path/to/filter')); ### before_post_render -execute ก่อนการ render ของโพสต์ สำหรับขั้นตอนของ execution ไปดูท่ี [post rendering](posts.html#Render) ได้ +execute ก่อนการ render ของโพสต์ สำหรับขั้นตอนของ execution ไปดูท่ี [post rendering](posts.html#Render) ได้ ยกตัวอย่างเช่น การเปลี่ยนตัวอักษรเป็นตัวเล็ก: -``` js -hexo.extend.filter.register('before_post_render', function(data){ +```js +hexo.extend.filter.register("before_post_render", function (data) { data.title = data.title.toLowerCase(); return data; }); @@ -112,9 +111,12 @@ execute หลังการ render ของโพสต์ สำหรับ ยกตัวอย่างเช่น แทน `@username` ด้วยลิงค์ท่ีชึ้ไปถึงโปรไฟล์ของ Twitter -``` js -hexo.extend.filter.register('after_post_render', function(data){ - data.content = data.content.replace(/@(\d+)/, '<a href="http://twitter.com/$1">#$1</a>'); +```js +hexo.extend.filter.register("after_post_render", function (data) { + data.content = data.content.replace( + /@(\d+)/, + '<a href="http://twitter.com/$1">#$1</a>', + ); return data; }); ``` @@ -123,8 +125,8 @@ hexo.extend.filter.register('after_post_render', function(data){ execute ก่อนการท่ีจะจบการใช้โปรแกรม hexo -- รันหลังการเรียก `hexo.exit` -``` js -hexo.extend.filter.register('before_exit', function(){ +```js +hexo.extend.filter.register("before_exit", function () { // ... }); ``` @@ -133,8 +135,8 @@ hexo.extend.filter.register('before_exit', function(){ execute ก่อนการเริ่มต้นของ generation -``` js -hexo.extend.filter.register('before_generate', function(){ +```js +hexo.extend.filter.register("before_generate", function () { // ... }); ``` @@ -143,21 +145,20 @@ hexo.extend.filter.register('before_generate', function(){ execute หลังการเสร็จสิ้นของ generation -``` js -hexo.extend.filter.register('after_generate', function(){ +```js +hexo.extend.filter.register("after_generate", function () { // ... }); ``` ### template_locals - แก้ไข [local variables](../docs/variables.html) ใน template ยกตัวอย่างเช่น เพิ่มเวลาปัจจุบันไปถึง local variable ของ template -``` js -hexo.extend.filter.register('template_locals', function(locals){ +```js +hexo.extend.filter.register("template_locals", function (locals) { locals.now = Date.now(); return locals; }); @@ -167,8 +168,8 @@ hexo.extend.filter.register('template_locals', function(locals){ execute หลัง initialization ของ hexo -- รันหลังการเสร็จสิ้นของ `hexo.init` -``` js -hexo.extend.filter.register('after_init', function(){ +```js +hexo.extend.filter.register("after_init", function () { // ... }); ``` @@ -177,8 +178,8 @@ hexo.extend.filter.register('after_init', function(){ execute เพิ่อให้ path แก่โพสต์ใหม่เมื่อการสร้่างโพสต์ใหม่มา -``` js -hexo.extend.filter.register('new_post_path', function(data, replace){ +```js +hexo.extend.filter.register("new_post_path", function (data, replace) { // ... }); ``` @@ -187,36 +188,36 @@ hexo.extend.filter.register('new_post_path', function(data, replace){ ใช้มาเพื่อสร้างลิงค์ถาวรของโพสต์ -``` js -hexo.extend.filter.register('post_permalink', function(data){ +```js +hexo.extend.filter.register("post_permalink", function (data) { // ... }); ``` ### after_render - execute หลังการเสร็จสิ้นของ rendering สำหรับข้อมูลเพิ่มเติม ไปดูได้ที่ [rendering](rendering.html#after_render_Filters) +execute หลังการเสร็จสิ้นของ rendering สำหรับข้อมูลเพิ่มเติม ไปดูได้ที่ [rendering](rendering.html#after_render_Filters) ### after_clean execute หลัง generation ของไฟล์ และ cache จะลบออกด้วยคำสั่ง `hexo clean` -``` js -hexo.extend.filter.register('after_clean', function(){ +```js +hexo.extend.filter.register("after_clean", function () { // remove some other temporary files }); ``` ### server_middleware -เพิ่ม middleware ไปถึง server `app` เป็น instance ของ [Connect] +เพิ่ม middleware ไปถึง server `app` เป็น instance ของ [Connect] ยกตัวอย่างเช่น เพิ่ม `X-Powered-By: Hexo` ไปให้ response header: -``` js -hexo.extend.filter.register('server_middleware', function(app){ - app.use(function(req, res, next){ - res.setHeader('X-Powered-By', 'Hexo'); +```js +hexo.extend.filter.register("server_middleware", function (app) { + app.use(function (req, res, next) { + res.setHeader("X-Powered-By", "Hexo"); next(); }); }); diff --git a/source/th/api/generator.md b/source/th/api/generator.md index e6e943fd88..2272d89be5 100644 --- a/source/th/api/generator.md +++ b/source/th/api/generator.md @@ -1,12 +1,13 @@ --- title: Generator --- + generator สร้าง route บนพื้นฐานของไฟล์ท่ีได้จัดการ ## Synopsis -``` js -hexo.extend.generator.register(name, function(locals){ +```js +hexo.extend.generator.register(name, function (locals) { // ... }); ``` @@ -15,27 +16,27 @@ argument `locals` จะส่งเข้า function โดยมี [site var ## Update Routes -``` js -hexo.extend.generator.register('test', function(locals){ +```js +hexo.extend.generator.register("test", function (locals) { // Object return { - path: 'foo', - data: 'foo' + path: "foo", + data: "foo", }; // Array return [ - {path: 'foo', data: 'foo'}, - {path: 'bar', data: 'bar'} + { path: "foo", data: "foo" }, + { path: "bar", data: "bar" }, ]; }); ``` -Attribute | Description ---- | --- -`path` | Path not including the prefixing `/`. -`data` | Data -`layout` | Layout. Specify the layouts for rendering. The value can be a string or an array. If it's ignored then the route will return `data` directly. +| Attribute | Description | +| --------- | --------------------------------------------------------------------------------------------------------------------------------------------- | +| `path` | Path not including the prefixing `/`. | +| `data` | Data | +| `layout` | Layout. Specify the layouts for rendering. The value can be a string or an array. If it's ignored then the route will return `data` directly. | เมื่ออัปเดท source file แฃ้ว hexo จะ execute generator ทั้งหมดและสร้างขึ้น route ใหม่ **กรุณาอย่าเข้าถึง router โดยตรง** @@ -43,17 +44,17 @@ Attribute | Description ### Archive Page -สร้างเพจ archive ได้ท่ี `archives/index.html` โพสต์จะเป็นแบบ data ท่ีส่งเข้า template. data นี้คล้ายกับ variable `page` ของ template +สร้างเพจ archive ได้ท่ี `archives/index.html` โพสต์จะเป็นแบบ data ท่ีส่งเข้า template. data นี้คล้ายกับ variable `page` ของ template -ต่อไปจะตั้งค่า attribute ของ `layout` เพื่อ render theme template เฉพาะ ในตัวอย่างต่อไปจะตั้งค่า layout อย่างนี้: ถ้า layout `archive` ไม่มี จะใช้ layout `index` แทน +ต่อไปจะตั้งค่า attribute ของ `layout` เพื่อ render theme template เฉพาะ ในตัวอย่างต่อไปจะตั้งค่า layout อย่างนี้: ถ้า layout `archive` ไม่มี จะใช้ layout `index` แทน -``` js -hexo.extend.generator.register('archive', function(locals){ +```js +hexo.extend.generator.register("archive", function (locals) { return { - path: 'archives/index.html', + path: "archives/index.html", data: locals, - layout: ['archive', 'index'] - } + layout: ["archive", "index"], + }; }); ``` @@ -61,15 +62,15 @@ hexo.extend.generator.register('archive', function(locals){ ผู้ใช้สามารถใช้เครื่องมือทางการ [hexo-pagination] อย่างสะดวกไปสร้างเพจ archive ท่ีมีหมายเลขหน้า -``` js -var pagination = require('hexo-pagination'); +```js +var pagination = require("hexo-pagination"); -hexo.extend.generator.register('archive', function(locals){ +hexo.extend.generator.register("archive", function (locals) { // hexo-pagination makes an index.html for the /archives route - return pagination('archives', locals.posts, { + return pagination("archives", locals.posts, { perPage: 10, - layout: ['archive', 'index'], - data: {} + layout: ["archive", "index"], + data: {}, }); }); ``` @@ -78,13 +79,13 @@ hexo.extend.generator.register('archive', function(locals){ โพสต์ทั้งหมดจะมีอยู่ใน `locals.posts` ด้วยแล้วจะสร้าง route ให้โพสต์ทั้งหมด -``` js -hexo.extend.generator.register('post', function(locals){ - return locals.posts.map(function(post){ +```js +hexo.extend.generator.register("post", function (locals) { + return locals.posts.map(function (post) { return { path: post.path, data: post, - layout: 'post' + layout: "post", }; }); }); @@ -92,17 +93,17 @@ hexo.extend.generator.register('post', function(locals){ ### Copy Files -คราวนี้ `data` จะเป็น function และ route `fs.ReadStream` ของ `data` จะสร้างขึ้นมาในเวลาที่ต้องการ +คราวนี้ `data` จะเป็น function และ route `fs.ReadStream` ของ `data` จะสร้างขึ้นมาในเวลาที่ต้องการ -``` js -var fs = require('hexo-fs'); +```js +var fs = require("hexo-fs"); -hexo.extend.generator.register('asset', function(locals){ +hexo.extend.generator.register("asset", function (locals) { return { - path: 'file.txt', - data: function(){ - return fs.createReadStream('path/to/file.txt') - } + path: "file.txt", + data: function () { + return fs.createReadStream("path/to/file.txt"); + }, }; }); ``` diff --git a/source/th/api/helper.md b/source/th/api/helper.md index 109d52b62c..5e0683a639 100644 --- a/source/th/api/helper.md +++ b/source/th/api/helper.md @@ -1,25 +1,26 @@ --- title: Helper --- + helper ทำให้ผู้ใช้เพิ่ม snippet เข้า template ของตนได้ง่ายขึ้น. เมื่อต้องจัดการ code ท่ีซับซ้อนขึ้น การใช้ helper จะสะดวกกว่าท่ีใช้ template ผู้ใช้จะเข้าถึง helper โดยไฟล์ `source` ไม่ได้ ## Synopsis -``` js -hexo.extend.helper.register(name, function(){ +```js +hexo.extend.helper.register(name, function () { // ... }); ``` ## Example -``` js -hexo.extend.helper.register('js', function(path){ +```js +hexo.extend.helper.register("js", function (path) { return '<script src="' + path + '"></script>'; }); ``` -``` js +```js <%- js('script.js') %> // <script src="script.js"></script> ``` @@ -34,8 +35,8 @@ Place it under `scripts/` or `themes/<yourtheme>/scripts/` folder. All helpers are executed in the same context. For example, to use [`url_for()`](/docs/helpers#url-for) inside a custom helper: -``` js -hexo.extend.helper.register('lorem', function(path) { +```js +hexo.extend.helper.register("lorem", function (path) { return '<script src="' + this.url_for(path) + '"></script>'; }); ``` @@ -44,6 +45,6 @@ hexo.extend.helper.register('lorem', function(path) { `hexo.extend.helper.get` will return the helper function, but it needs to have hexo as its context, so: -``` js -const url_for = hexo.extend.helper.get('url_for').bind(hexo); +```js +const url_for = hexo.extend.helper.get("url_for").bind(hexo); ``` diff --git a/source/th/api/index.md b/source/th/api/index.md index 704c3e6a84..057bedcb0f 100644 --- a/source/th/api/index.md +++ b/source/th/api/index.md @@ -2,72 +2,75 @@ title: API --- - บทความนี้แนะนำข้อมูลเกี่ยวกับ API และมีส่วนช่วยต่อผู้ใช้ท่ีอยากปรับ source code ของ hexo หรือเขียนปลั๊กอินใหม่ ถ้าคุณสนใจวิธีการใช้้พื้นฐานของ hexo กรุณาไปอ่น [docs](../docs) แทน +บทความนี้แนะนำข้อมูลเกี่ยวกับ API และมีส่วนช่วยต่อผู้ใช้ท่ีอยากปรับ source code ของ hexo หรือเขียนปลั๊กอินใหม่ ถ้าคุณสนใจวิธีการใช้้พื้นฐานของ hexo กรุณาไปอ่น [docs](../docs) แทน บทความนี้สำหรับ hexo 3 หรือเวอร์ชั่นใหม่กว่านี้เท่านั้น ## Initialize -ขั้นตอนแรกคือการสร้าง instance ของ hexo. instance -จะประกอบด้วยสองส่วน:`base_dir` ซึ่งเป็น root directory ของเว็บไซต์ และ object ท่ีมี initialization options ขั้นตอนท่ีสองใช้วิธี `init`เพื่อ initialize instance ด้วยวิธีนี้ hexo จะโหลด configuration และปลั๊กอินของมัน +ขั้นตอนแรกคือการสร้าง instance ของ hexo. instance +จะประกอบด้วยสองส่วน:`base_dir` ซึ่งเป็น root directory ของเว็บไซต์ และ object ท่ีมี initialization options ขั้นตอนท่ีสองใช้วิธี `init`เพื่อ initialize instance ด้วยวิธีนี้ hexo จะโหลด configuration และปลั๊กอินของมัน -``` js -var Hexo = require('hexo'); +```js +var Hexo = require("hexo"); var hexo = new Hexo(process.cwd(), {}); -hexo.init().then(function(){ +hexo.init().then(function () { // ... }); ``` -Option | Description | Default ---- | --- | --- -`debug` | Enable debug mode. Display debug messages in the terminal and save `debug.log` in the root directory. | `false` -`safe` | Enable safe mode. Don't load any plugins. | `false` -`silent` | Enable silent mode. Don't display any messages in the terminal. | `false` -`config` | Specify the path of the configuration file. | `_config.yml` -`draft` / `drafts`| Enable to add drafts to the posts list.<br> example: when you use `hexo.locals.get('posts')` | `render_drafts` of _config.yml +| Option | Description | Default | +| ------------------ | ----------------------------------------------------------------------------------------------------- | ------------------------------- | +| `debug` | Enable debug mode. Display debug messages in the terminal and save `debug.log` in the root directory. | `false` | +| `safe` | Enable safe mode. Don't load any plugins. | `false` | +| `silent` | Enable silent mode. Don't display any messages in the terminal. | `false` | +| `config` | Specify the path of the configuration file. | `_config.yml` | +| `draft` / `drafts` | Enable to add drafts to the posts list.<br> example: when you use `hexo.locals.get('posts')` | `render_drafts` of \_config.yml | ## Load Files -hexo โหลดไฟล์ด้วยสองวิธี: `load` และ `watch` . วิธี `load` ใช้มาเพื่อโหลดไฟล์ใน folder `source` และ data ของธีม ส่วนวิธี `watch` ทำเรื่องเดียวกันกับวิธี `load` แต่จะเริ่มบันทึกการเปลี่ยนแปลงของไฟล์อย่างต่อเนื่อง +hexo โหลดไฟล์ด้วยสองวิธี: `load` และ `watch` . วิธี `load` ใช้มาเพื่อโหลดไฟล์ใน folder `source` และ data ของธีม ส่วนวิธี `watch` ทำเรื่องเดียวกันกับวิธี `load` แต่จะเริ่มบันทึกการเปลี่ยนแปลงของไฟล์อย่างต่อเนื่อง ทั้งสองวิธีนี้จะโหลด list ของไฟล์และส่งไฟล์เข้า processor ท่ีเกี่ยวข้อง หลังการ process ของไฟล์ทั้งหมด จะมี generator มาสร้าง route -``` js -hexo.load().then(function(){ +```js +hexo.load().then(function () { // ... }); -hexo.watch().then(function(){ +hexo.watch().then(function () { // You can call hexo.unwatch() later to stop watching. }); ``` ## Execute Commands -ด้วยวิธี `call` ผู้ใช้สามารถเรียกคำสั่ง console สำหรับ instance ของ hexo การเรียกคำสั่ง console นี้ประกอบด้วยสอง argument: ชื่อคำสั่ง console และ argument ของ option คำสั่ง console ที่แตกต่างกันนั้นจะมี option ท่ีแตกต่างกัน +ด้วยวิธี `call` ผู้ใช้สามารถเรียกคำสั่ง console สำหรับ instance ของ hexo การเรียกคำสั่ง console นี้ประกอบด้วยสอง argument: ชื่อคำสั่ง console และ argument ของ option คำสั่ง console ที่แตกต่างกันนั้นจะมี option ท่ีแตกต่างกัน -``` js -hexo.call('generate', {}).then(function(){ +```js +hexo.call("generate", {}).then(function () { // ... }); ``` -``` js -hexo.call('list', { _: ['post'] }).then(function() { +```js +hexo.call("list", { _: ["post"] }).then(function () { // ... -}) +}); ``` ## Exit ด้วยวิธี `exit` คุณสามารถจบคำสั่ง console อย่างสง่างามและทำสิ่งสำคัญให้ เช่นการบันทึก database -``` js -hexo.call('generate').then(function(){ - return hexo.exit(); -}).catch(function(err){ - return hexo.exit(err); -}); +```js +hexo + .call("generate") + .then(function () { + return hexo.exit(); + }) + .catch(function (err) { + return hexo.exit(err); + }); ``` diff --git a/source/th/api/injector.md b/source/th/api/injector.md index 04f45be3ce..c44a869b40 100644 --- a/source/th/api/injector.md +++ b/source/th/api/injector.md @@ -7,7 +7,7 @@ An injector is used to add static code snippet to the `<head>` or/and `<body>` o ## Synopsis ```js -hexo.extend.injector.register(entry, value, to) +hexo.extend.injector.register(entry, value, to); ``` ### entry `<string>` @@ -40,24 +40,34 @@ Which page will code snippets being injected. - `tag`: Only inject to tag pages (which has `is_tag()` helper being `true`) - Custom layout name could be used as well, see [Writing - Layout](writing#Layout). ----- +--- There are other internal functions, see [hexojs/hexo#4049](https://github.com/hexojs/hexo/pull/4049) for more details. ## Example ```js -const css = hexo.extend.helper.get('css').bind(hexo); -const js = hexo.extend.helper.get('js').bind(hexo); - -hexo.extend.injector.register('head_end', () => { - return css('https://cdn.jsdelivr.net/npm/aplayer@1.10.1/dist/APlayer.min.css'); -}, 'music'); - -hexo.extend.injector.register('body_end', '<script src="https://cdn.jsdelivr.net/npm/aplayer@1.10.1/dist/APlayer.min.js">', 'music'); - -hexo.extend.injector.register('body_end', () => { - return js('/js/jquery.js'); +const css = hexo.extend.helper.get("css").bind(hexo); +const js = hexo.extend.helper.get("js").bind(hexo); + +hexo.extend.injector.register( + "head_end", + () => { + return css( + "https://cdn.jsdelivr.net/npm/aplayer@1.10.1/dist/APlayer.min.css", + ); + }, + "music", +); + +hexo.extend.injector.register( + "body_end", + '<script src="https://cdn.jsdelivr.net/npm/aplayer@1.10.1/dist/APlayer.min.js">', + "music", +); + +hexo.extend.injector.register("body_end", () => { + return js("/js/jquery.js"); }); ``` @@ -69,10 +79,10 @@ Use any of the following options: 1. -``` js -const css = hexo.extend.helper.get('css').bind(hexo); +```js +const css = hexo.extend.helper.get("css").bind(hexo); -hexo.extend.injector.register('head_end', () => { +hexo.extend.injector.register("head_end", () => { const { cssPath } = hexo.config.fooPlugin; return css(cssPath); }); @@ -80,23 +90,23 @@ hexo.extend.injector.register('head_end', () => { 2. -``` js index.js +```js index.js /* global hexo */ -hexo.extend.injector.register('head_end', require('./lib/inject').bind(hexo)) +hexo.extend.injector.register("head_end", require("./lib/inject").bind(hexo)); ``` -``` js lib/inject.js +```js lib/inject.js module.exports = function () { - const css = this.extend.helper.get('css'); + const css = this.extend.helper.get("css"); const { cssPath } = this.config.fooPlugin; return css(cssPath); -} +}; ``` -``` js lib/inject.js +```js lib/inject.js function injectFn() { - const css = this.extend.helper.get('css'); + const css = this.extend.helper.get("css"); const { cssPath } = this.config.fooPlugin; return css(cssPath); } @@ -106,23 +116,23 @@ module.exports = injectFn; 3. -``` js index.js +```js index.js /* global hexo */ -hexo.extend.injector.register('head_end', require('./lib/inject')(hexo)) +hexo.extend.injector.register("head_end", require("./lib/inject")(hexo)); ``` -``` js lib/inject.js +```js lib/inject.js module.exports = (hexo) => () => { - const css = hexo.extend.helper.get('css').bind(hexo); + const css = hexo.extend.helper.get("css").bind(hexo); const { cssPath } = hexo.config.fooPlugin; return css(cssPath); }; ``` -``` js lib/inject.js +```js lib/inject.js const injectFn = (hexo) => { - const css = hexo.extend.helper.get('css').bind(hexo); + const css = hexo.extend.helper.get("css").bind(hexo); const { cssPath } = hexo.config.fooPlugin; return css(cssPath); }; diff --git a/source/th/api/locals.md b/source/th/api/locals.md index 3ec39c3eb1..59ece21677 100644 --- a/source/th/api/locals.md +++ b/source/th/api/locals.md @@ -6,22 +6,22 @@ local variable จะใช้มาเป็น template rendering ซึ่ง ## Default Variables -Variable | Description ---- | --- -`posts` | All posts -`pages` | All pages -`categories` | All categories -`tags` | All tags +| Variable | Description | +| ------------ | -------------- | +| `posts` | All posts | +| `pages` | All pages | +| `categories` | All categories | +| `tags` | All tags | ## Get a Variable -``` js -hexo.locals.get('posts') +```js +hexo.locals.get("posts"); ``` ## Set a Variable -``` js +```js hexo.locals.set('posts', function(){ return ... }); @@ -29,18 +29,18 @@ hexo.locals.set('posts', function(){ ## Remove a Variable -``` js -hexo.locals.remove('posts'); +```js +hexo.locals.remove("posts"); ``` ## Get All Variable -``` js +```js hexo.locals.toObject(); ``` ## Invalidate the cache -``` js +```js hexo.locals.invalidate(); ``` diff --git a/source/th/api/migrator.md b/source/th/api/migrator.md index 6fae92c4a8..ad28917e28 100644 --- a/source/th/api/migrator.md +++ b/source/th/api/migrator.md @@ -1,12 +1,13 @@ --- title: Migrator --- + migrator ช่วยให้ผู้ใช้ย้าย data จากระบบอื่นมาเข้า hexo ## Synopsis -``` js -hexo.extend.migrator.register(name, function(args){ +```js +hexo.extend.migrator.register(name, function (args) { // ... }); ``` diff --git a/source/th/api/posts.md b/source/th/api/posts.md index 5967ff2be2..f5cb7e3177 100644 --- a/source/th/api/posts.md +++ b/source/th/api/posts.md @@ -1,57 +1,58 @@ --- title: Posts --- + ## Create a New Post -``` js +```js hexo.post.create(data, replace); ``` -Argument | Description ---- | --- -`data` | Data -`replace` | Replace existing files +| Argument | Description | +| --------- | ---------------------- | +| `data` | Data | +| `replace` | Replace existing files | attribute ของโพสต์จะตั้งค่าอยู่ใน `data` ตารางต่อไปไม่ละเอียดถี่ถ้วนและ attribute อื่นๆสามารถเพิ่มใส่เข้าไปใน front-matter ได้ -Data | Description ---- | --- -`title` | Title -`slug` | URL -`layout` | Layout. Defaults to the `default_layout` setting. -`path` | Path. Hexo builds the post path based on the `new_post_path` setting by default. -`date` | Date. Defaults to the current date. +| Data | Description | +| -------- | -------------------------------------------------------------------------------- | +| `title` | Title | +| `slug` | URL | +| `layout` | Layout. Defaults to the `default_layout` setting. | +| `path` | Path. Hexo builds the post path based on the `new_post_path` setting by default. | +| `date` | Date. Defaults to the current date. | ## Publish a Draft -``` js +```js hexo.post.publish(data, replace); ``` -Argument | Description ---- | --- -`data` | Data -`replace` | Replace existing files +| Argument | Description | +| --------- | ---------------------- | +| `data` | Data | +| `replace` | Replace existing files | attribute ของโพสต์จะตั้งค่าอยู่ใน data ตารางต่อไปไม่ละเอียดถี่ถ้วนและ attribute อื่นๆสามารถเพิ่มใส่เข้าไปใน front-matter ได้ -Data | Description ---- | --- -`slug` | File name (Required) -`layout` | Layout. Defaults to the `default_layout` setting. +| Data | Description | +| -------- | ------------------------------------------------- | +| `slug` | File name (Required) | +| `layout` | Layout. Defaults to the `default_layout` setting. | ## Render -``` js +```js hexo.post.render(source, data); ``` -Argument | Description ---- | --- -`source` | Full path of a file (Optional) -`data` | Data +| Argument | Description | +| -------- | ------------------------------ | +| `source` | Full path of a file (Optional) | +| `data` | Data | - data ต้องการมี attribute `content` ถ้าไม่มี hexo จะลองอ่านไฟล์ที่เป็นต้นฉบับ ขั้นตอน execution ของ function นี้จะดังต่อไปนี้ +data ต้องการมี attribute `content` ถ้าไม่มี hexo จะลองอ่านไฟล์ที่เป็นต้นฉบับ ขั้นตอน execution ของ function นี้จะดังต่อไปนี้ - Execute `before_post_render` filters execute - Render with Markdown or other renderers (depending on the extension name) diff --git a/source/th/api/processor.md b/source/th/api/processor.md index 3bb1e904c5..c9c99c09c1 100644 --- a/source/th/api/processor.md +++ b/source/th/api/processor.md @@ -1,13 +1,14 @@ --- title: Processor --- + processor ใช้มาจัดการไฟล์ source ท่ีอยู่ใน folder `source` ## Synopsis -``` js -hexo.extend.processor.register(rule, function(file){ - // ... +```js +hexo.extend.processor.register(rule, function (file) { + // ... }); ``` diff --git a/source/th/api/renderer.md b/source/th/api/renderer.md index 501b4bc09f..161792d217 100644 --- a/source/th/api/renderer.md +++ b/source/th/api/renderer.md @@ -1,70 +1,85 @@ --- title: Renderer --- + renderer ใช้มา render เนื้อหา ## Synopsis -``` js -hexo.extend.renderer.register(name, output, function(data, options){ - // ... -}, sync); +```js +hexo.extend.renderer.register( + name, + output, + function (data, options) { + // ... + }, + sync, +); ``` -Argument | Description ---- | --- -`name` | Input filename extension (lower case, without leading `.`) -`output` | Output filename extension (lower case, without leading `.`) -`sync` | Sync mode +| Argument | Description | +| -------- | ----------------------------------------------------------- | +| `name` | Input filename extension (lower case, without leading `.`) | +| `output` | Output filename extension (lower case, without leading `.`) | +| `sync` | Sync mode | argument สองตัวนั้นจะส่งเข้า render function: -Argument | Description ---- | --- -`data` | Include two attributes: file path `path` and file content `text`. `path` won't necessarily exist. -`option` | Options +| Argument | Description | +| -------- | ------------------------------------------------------------------------------------------------- | +| `data` | Include two attributes: file path `path` and file content `text`. `path` won't necessarily exist. | +| `option` | Options | ## ตัวอย่าง ### โหมด async -``` js -var stylus = require('stylus'); +```js +var stylus = require("stylus"); // Callback -hexo.extend.renderer.register('styl', 'css', function(data, options, callback){ - stylus(data.text).set('filename', data.path).render(callback); -}); +hexo.extend.renderer.register( + "styl", + "css", + function (data, options, callback) { + stylus(data.text).set("filename", data.path).render(callback); + }, +); // Promise -hexo.extend.renderer.register('styl', 'css', function(data, options){ - return new Promise(function(resolve, reject){ - resolve('test'); +hexo.extend.renderer.register("styl", "css", function (data, options) { + return new Promise(function (resolve, reject) { + resolve("test"); }); }); ``` ### โหมด sync -``` js -var ejs = require('ejs'); - -hexo.extend.renderer.register('ejs', 'html', function(data, options){ - options.filename = data.path; - return ejs.render(data.text, options); -}, true); +```js +var ejs = require("ejs"); + +hexo.extend.renderer.register( + "ejs", + "html", + function (data, options) { + options.filename = data.path; + return ejs.render(data.text, options); + }, + true, +); ``` ### Disable Nunjucks tags Nunjucks tags `{{ }}` or `{% %}` (utilized by [tag plugin](/docs/tag-plugins)) are processed by default, to disable: -``` js +```js function lessFn(data, options) { // do something } -lessFn.disableNunjucks = true +lessFn.disableNunjucks = true; -hexo.extend.renderer.register('less', 'css', lessFn); +hexo.extend.renderer.register("less", "css", lessFn); ``` diff --git a/source/th/api/rendering.md b/source/th/api/rendering.md index 94a1cbf159..41e5d6db6d 100644 --- a/source/th/api/rendering.md +++ b/source/th/api/rendering.md @@ -1,14 +1,15 @@ --- title: Rendering --- -มีทั้งหมดสองวิธีสำหรับการ render ไฟล์หรือ string ใน hexo : `hexo.render.render`ท่ีเป็น asynchronous และวิธี `hexo.render.renderSync` ท่ีเป็น synchronous เนื่องจากว่าสองวิธีนี้คล้ายกันมาก ก็เลยมีการอธิบายแต่ `hexo.render.render` ท่ีเป็นวิธี asynchronous เท่านั้นในย่อหน้าต่อไป + +มีทั้งหมดสองวิธีสำหรับการ render ไฟล์หรือ string ใน hexo : `hexo.render.render`ท่ีเป็น asynchronous และวิธี `hexo.render.renderSync` ท่ีเป็น synchronous เนื่องจากว่าสองวิธีนี้คล้ายกันมาก ก็เลยมีการอธิบายแต่ `hexo.render.render` ท่ีเป็นวิธี asynchronous เท่านั้นในย่อหน้าต่อไป ## Render a String เวลา render string ผู้ใช้ต้องบ่งชี้ถึง `engine` ท่ีชัดเจนเพื่อทำให้ hexo เข้าใจว่าต้องใช้ rendering engine ตัวใหน -``` js -hexo.render.render({text: 'example', engine: 'swig'}).then(function(result){ +```js +hexo.render.render({ text: "example", engine: "swig" }).then(function (result) { // ... }); ``` @@ -17,8 +18,8 @@ hexo.render.render({text: 'example', engine: 'swig'}).then(function(result){ เมื่อ render ไฟล์ จะไม่ต้องชี้ `engine` ให้ชั้ดเจน เพราะว่า hexo จะค้นหา rendering engine ท่ีเกี่ยวข้องตาม extension ของไฟล์โดยอัตโนมัติ แต่ถ้าชี้ `engine` ให้ชั้ดเจนก็ไม่มีปัญหา -``` js -hexo.render.render({path: 'path/to/file.swig'}).then(function(result){ +```js +hexo.render.render({ path: "path/to/file.swig" }).then(function (result) { // ... }); ``` @@ -27,8 +28,8 @@ hexo.render.render({path: 'path/to/file.swig'}).then(function(result){ ผู้ใช้สามารถส่ง options object เข้าไปเป็น argument ท่ีสอง -``` js -hexo.render.render({text: ''}, {foo: 'foo'}).then(function(result){ +```js +hexo.render.render({ text: "" }, { foo: "foo" }).then(function (result) { // ... }); ``` @@ -37,10 +38,10 @@ hexo.render.render({text: ''}, {foo: 'foo'}).then(function(result){ เมื่อเสร็จการ rendering hexo จะ execute filter `after_render` ยกตัวอย่างเช่น ผู้ใช้สามารถ implement a JavaScript minifier ด้วยลักษณะนี้ -``` js -var UglifyJS = require('uglify-js'); +```js +var UglifyJS = require("uglify-js"); -hexo.extend.filter.register('after_render:js', function(str, data){ +hexo.extend.filter.register("after_render:js", function (str, data) { var result = UglifyJS.minify(str); return result.code; }); @@ -48,32 +49,32 @@ hexo.extend.filter.register('after_render:js', function(str, data){ ## Check Whether a File is Renderable -ผู้ใช้สามารถใช้วิธี `isRenderable` หรือ `isRenderableSync` ไปตรวจว่าไฟล์นั้น renderable หรือไม่ เมื่อมี renderer ท่ีเกี่ยวข้อง ผลท่ีส่งกลับจะเป็น true +ผู้ใช้สามารถใช้วิธี `isRenderable` หรือ `isRenderableSync` ไปตรวจว่าไฟล์นั้น renderable หรือไม่ เมื่อมี renderer ท่ีเกี่ยวข้อง ผลท่ีส่งกลับจะเป็น true -``` js -hexo.render.isRenderable('layout.swig') // true -hexo.render.isRenderable('image.png') // false +```js +hexo.render.isRenderable("layout.swig"); // true +hexo.render.isRenderable("image.png"); // false ``` ## Get the Output Extension - ผู้ใช้สามารถได้ rendered output ด้วยวิธี `getOutput` ถ้าไฟล์ไม่ใช่ renderable ผลท่ีส่งกลับด้วยวิธีนี้จะเป็น empty string +ผู้ใช้สามารถได้ rendered output ด้วยวิธี `getOutput` ถ้าไฟล์ไม่ใช่ renderable ผลท่ีส่งกลับด้วยวิธีนี้จะเป็น empty string -``` js -hexo.render.getOutput('layout.swig') // html -hexo.render.getOutput('image.png') // ''' +```js +hexo.render.getOutput("layout.swig"); // html +hexo.render.getOutput("image.png"); // ''' ``` ## Disable Nunjucks tags If you are not using a [tag plugin](/docs/tag-plugins) and want to use `{{ }}` or `{% %}` in your post without using content [escaping](/docs/troubleshooting#Escape-Contents), you can disable processing of Nunjucks tag in existing renderer by: -``` js +```js // following example only applies to '.md' file extension // you may need to cover other extensions, e.g. '.markdown', '.mkd', etc -const renderer = hexo.render.renderer.get('md') +const renderer = hexo.render.renderer.get("md"); if (renderer) { - renderer.disableNunjucks = true - hexo.extend.renderer.register('md', 'html', renderer) + renderer.disableNunjucks = true; + hexo.extend.renderer.register("md", "html", renderer); } ``` diff --git a/source/th/api/router.md b/source/th/api/router.md index d745a62560..3f6b00be62 100644 --- a/source/th/api/router.md +++ b/source/th/api/router.md @@ -1,15 +1,16 @@ --- title: Router --- + router จะบันทึกและตั้งค่า path ทั้งหมดที่ใช้ในเว็บไซต์ ## Get a Path วิธี `get` จะส่งกลับผลที่เป็น [Stream] code ต่อไปเป็นตัวอย่างการบ่งบอก path ไปถึงหน้งเว็บเฉพาะ -``` js -var data = hexo.route.get('index.html'); -var dest = fs.createWriteStream('somewhere'); +```js +var data = hexo.route.get("index.html"); +var dest = fs.createWriteStream("somewhere"); data.pipe(dest); ``` @@ -18,32 +19,32 @@ data.pipe(dest); ตัวเลือกท่ีส่งเข้าวิธี `set` ต้องเป็น string [Buffer] หรือ function -``` js +```js // String -hexo.route.set('index.html', 'index') +hexo.route.set("index.html", "index"); // Buffer -hexo.route.set('index.html', new Buffer('index')); +hexo.route.set("index.html", new Buffer("index")); // Function (Promise) -hexo.route.set('index.html', function(){ - return new Promise(function(resolve, reject){ - resolve('index'); +hexo.route.set("index.html", function () { + return new Promise(function (resolve, reject) { + resolve("index"); }); }); // Function (Callback) -hexo.route.set('index.html', function(callback){ - callback(null, 'index'); +hexo.route.set("index.html", function (callback) { + callback(null, "index"); }); ``` -ผู้ใช้ส่ง boolean เข้าไปได้ว่า path นั้นจะถูกแก้ไขหรือเปล่า ดังนั้นการตั้งค่าท่ีเป็น boolean นี้จะช่วยเพิ่มความเร็วใน file generation เพราะว่าจะเลือกการไม่รันไฟล์ที่ unmodified ได้ +ผู้ใช้ส่ง boolean เข้าไปได้ว่า path นั้นจะถูกแก้ไขหรือเปล่า ดังนั้นการตั้งค่าท่ีเป็น boolean นี้จะช่วยเพิ่มความเร็วใน file generation เพราะว่าจะเลือกการไม่รันไฟล์ที่ unmodified ได้ -``` js -hexo.route.set('index.html', { - data: 'index', - modified: false +```js +hexo.route.set("index.html", { + data: "index", + modified: false, }); // hexo.route.isModified('index.html') => false @@ -51,13 +52,13 @@ hexo.route.set('index.html', { ## Remove a Path -``` js -hexo.route.remove('index.html'); +```js +hexo.route.remove("index.html"); ``` ## Get the List of Routes -``` js +```js hexo.route.list(); ``` @@ -65,8 +66,8 @@ hexo.route.list(); วิธี `format` จะเปลี่ยน string เป็น path ที่ถูกต้อง -``` js -hexo.route.format('archives/'); +```js +hexo.route.format("archives/"); // archives/index.html ``` diff --git a/source/th/api/scaffolds.md b/source/th/api/scaffolds.md index 11f991ef69..e7ba7c37c1 100644 --- a/source/th/api/scaffolds.md +++ b/source/th/api/scaffolds.md @@ -1,20 +1,21 @@ --- title: Scaffolds --- + ## Get a Scaffold -``` js +```js hexo.scaffold.get(name); ``` ## Set a Scaffold -``` js +```js hexo.scaffold.set(name, content); ``` ## Remove a Scaffold -``` js +```js hexo.scaffold.remove(name); ``` diff --git a/source/th/api/tag.md b/source/th/api/tag.md index a48a32ff37..e56365893a 100644 --- a/source/th/api/tag.md +++ b/source/th/api/tag.md @@ -1,38 +1,43 @@ --- title: Tag --- + tag ช่วยให้ผู้ใช้เสียบ snippet เข้าไปในโพสต์ของตนอย่างง่ายดายและรวดเร็ว ## Synopsis -``` js -hexo.extend.tag.register(name, function(args, content){ - // ... -}, options); +```js +hexo.extend.tag.register( + name, + function (args, content) { + // ... + }, + options, +); ``` -argument ทั้งหมดสองตัวจะส่งเข้า function แท็ก: `args` และ `content` `args` เป็น argument ท่ีส่งเข้าปลั๊กอินแท็กและ `content` เป็นเนื้อหาท่ีอยู่ในปลั๊กอินแท็ก จากคำแนะนำของ asynchronous rendering ใน hexo 3 รู้ได้ว่า hexo ใช้ [Nunjucks] เพื่อ rendering ซึ่งแตกต่างจาก rendering ใน [Swig] +argument ทั้งหมดสองตัวจะส่งเข้า function แท็ก: `args` และ `content` `args` เป็น argument ท่ีส่งเข้าปลั๊กอินแท็กและ `content` เป็นเนื้อหาท่ีอยู่ในปลั๊กอินแท็ก จากคำแนะนำของ asynchronous rendering ใน hexo 3 รู้ได้ว่า hexo ใช้ [Nunjucks] เพื่อ rendering ซึ่งแตกต่างจาก rendering ใน [Swig] ## Unregister Tags Use `unregister()` to replace existing [tag plugins](/docs/tag-plugins) with custom functions. -``` js +```js hexo.extend.tag.unregister(name); ``` **Example** -``` js +```js const tagFn = (args, content) => { - content = 'something'; + content = "something"; return content; }; // https://hexo.io/docs/tag-plugins#YouTube -hexo.extend.tag.unregister('youtube'); +hexo.extend.tag.unregister("youtube"); -hexo.extend.tag.register('youtube', tagFn); +hexo.extend.tag.register("youtube", tagFn); ``` ## Options @@ -51,10 +56,14 @@ hexo.extend.tag.register('youtube', tagFn); เสียบวิดีโอ youtube ลง -``` js -hexo.extend.tag.register('youtube', function(args){ +```js +hexo.extend.tag.register("youtube", function (args) { var id = args[0]; - return '<div class="video-container"><iframe width="560" height="315" src="http://www.youtube.com/embed/' + id + '" frameborder="0" allowfullscreen></iframe></div>'; + return ( + '<div class="video-container"><iframe width="560" height="315" src="http://www.youtube.com/embed/' + + id + + '" frameborder="0" allowfullscreen></iframe></div>' + ); }); ``` @@ -62,29 +71,43 @@ hexo.extend.tag.register('youtube', function(args){ เสียบ pull quote ลง -``` js -hexo.extend.tag.register('pullquote', function(args, content){ - var className = args.join(' '); - return '<blockquote class="pullquote' + className + '">' + content + '</blockquote>'; -}, {ends: true}); +```js +hexo.extend.tag.register( + "pullquote", + function (args, content) { + var className = args.join(" "); + return ( + '<blockquote class="pullquote' + + className + + '">' + + content + + "</blockquote>" + ); + }, + { ends: true }, +); ``` ### Async Rendering เสียบไฟล์ลง -``` js -var fs = require('hexo-fs'); -var pathFn = require('path'); - -hexo.extend.tag.register('include_code', function(args){ - var filename = args[0]; - var path = pathFn.join(hexo.source_dir, filename); - - return fs.readFile(path).then(function(content){ - return '<pre><code>' + content + '</code></pre>'; - }); -}, {async: true}); +```js +var fs = require("hexo-fs"); +var pathFn = require("path"); + +hexo.extend.tag.register( + "include_code", + function (args) { + var filename = args[0]; + var path = pathFn.join(hexo.source_dir, filename); + + return fs.readFile(path).then(function (content) { + return "<pre><code>" + content + "</code></pre>"; + }); + }, + { async: true }, +); ``` ## Front-matter and user configuration @@ -93,7 +116,7 @@ Any of the following options is valid: 1. -``` js +```js hexo.extend.tag.register('foo', function (args) { const [firstArg] = args; @@ -118,11 +141,11 @@ hexo.extend.tag.register('foo', function (args) { 2. -``` js index.js -hexo.extend.tag.register('foo', require('./lib/foo')(hexo)); +```js index.js +hexo.extend.tag.register("foo", require("./lib/foo")(hexo)); ``` -``` js lib/foo.js +```js lib/foo.js module.exports = hexo => { return function fooFn(args) { const [firstArg] = args; diff --git a/source/th/api/themes.md b/source/th/api/themes.md index 0f2094e2ae..60116ca7e2 100644 --- a/source/th/api/themes.md +++ b/source/th/api/themes.md @@ -1,23 +1,24 @@ --- title: Themes --- + `hexo.theme` สืบทอดจาก [Box](box.html) และสร้าง template ได้ ## Get a View -``` js +```js hexo.theme.getView(path); ``` ## Set a View -``` js +```js hexo.theme.setView(path, data); ``` ## Remove a View -``` js +```js hexo.theme.removeView(path); ``` @@ -25,10 +26,10 @@ hexo.theme.removeView(path); view มีสองวิธี: `render` และ `renderSync` ทั้งสองวิธีนี้เหมือนกัน แต่ตัวแรกเป็น asynchronous และตัวหลังเป็น synchronous ที่นี่จะพูดถึงแต่ `render` เท่านั้นเพื่อเป็นความเรียบง่าย -``` js -var view = hexo.theme.getView('layout.swig'); +```js +var view = hexo.theme.getView("layout.swig"); -view.render({foo: 1, bar: 2}).then(function(result){ +view.render({ foo: 1, bar: 2 }).then(function (result) { // ... }); ``` diff --git a/source/th/docs/asset-folders.md b/source/th/docs/asset-folders.md index ca26ec7c36..71bef807f4 100644 --- a/source/th/docs/asset-folders.md +++ b/source/th/docs/asset-folders.md @@ -1,6 +1,7 @@ --- title: Asset Folders --- + ## Global Asset Folder asset เป็นไฟล์ท่ี non-post และอยู่ใน folder `source` อย่่างเช่นไฟล์ images, @@ -12,17 +13,17 @@ CSS หรือ JavaScript ยกตัวอย่างเช่น ถ้า {% youtube feIDVQ2tz0o %} -ถ้าคุณอยากทำให้ asset ของแต่ละโพสต์อยู่ใน folder ท่ีแตกต่างกัน ไปตั้งค่า +ถ้าคุณอยากทำให้ asset ของแต่ละโพสต์อยู่ใน folder ท่ีแตกต่างกัน ไปตั้งค่า `post_asset_folder` ของไฟล์ `_config.yml` เป็น true ได้ -``` yaml _config.yml +```yaml _config.yml post_asset_folder: true ``` ถ้าเปิดการเฝ้าดู asset folder แล้ว hexo จะสร้าง folder ให้ทุกครั้งท่ีคุณสร้างโพสต์ใหม่ด้วยคำสั่ง `hexo new [layout] <title>` asset folder นี้จะมีชื่อเดียวกันกับไฟล์ markdown ท่ีเป็นโพสต์นั้น -อย่างนี้คุณจะได้วาง asset ทั้งหมดของโพสต์นั้นอยู่ใน folder และอ้างอิง asset +อย่างนี้คุณจะได้วาง asset ทั้งหมดของโพสต์นั้นอยู่ใน folder และอ้างอิง asset ด้วย relative path ## Tag Plugins For Relative Path Referencing @@ -40,10 +41,10 @@ asset folder นี้จะมีชื่อเดียวกันกับ {% asset_link slug [title] %} ``` -ยกตัวอย่างเช่น ถ้าสร้าง asset folder แล้ว วางรูปภาพ `example.jpg` เข้าอยู่ใน - asset folder ของคุณ และใช้ syntax ของ markdown ท่ีเป็น `![](example.jpg)` - เพื่ออ้างอิงรูปภาพ แต่ syntax นี้จะไม่สามารถทำให้รูปภาพนั้นอยู่ในเพจ index - อย่างถูกต้อง +ยกตัวอย่างเช่น ถ้าสร้าง asset folder แล้ว วางรูปภาพ `example.jpg` เข้าอยู่ใน +asset folder ของคุณ และใช้ syntax ของ markdown ท่ีเป็น `![](example.jpg)` +เพื่ออ้างอิงรูปภาพ แต่ syntax นี้จะไม่สามารถทำให้รูปภาพนั้นอยู่ในเพจ index +อย่างถูกต้อง วิธีที่ถูกต้องสำหรับการอ้างอิงรูปภาพคือใช้ปลั๊อินแท็ก ไม่ใช่ markdown: @@ -60,7 +61,7 @@ asset folder นี้จะมีชื่อเดียวกันกับ To enable: -``` yml _config.yml +```yml _config.yml post_asset_folder: true marked: prependRoot: true diff --git a/source/th/docs/commands.md b/source/th/docs/commands.md index 99af55fa76..562876d955 100644 --- a/source/th/docs/commands.md +++ b/source/th/docs/commands.md @@ -1,9 +1,10 @@ --- title: Commands --- + ## init -``` bash +```bash $ hexo init [folder] ``` @@ -17,32 +18,32 @@ This command is a shortcut that runs the following steps: ## new -``` bash +```bash $ hexo new [layout] <title> ``` สร้างบทความใหม่. -ถ้าไม่ได้ตั้งค่าชั้ดเจน hexo จะใช้ `default_layout` ของไฟล์ [_config.yml](configuration.html) -ถ้า `title` ของบทความนั้นมี space จะต้องห่อ `title` นั้นด้วยเครื่องหมายอ้างอิง +ถ้าไม่ได้ตั้งค่าชั้ดเจน hexo จะใช้ `default_layout` ของไฟล์ [\_config.yml](configuration.html) +ถ้า `title` ของบทความนั้นมี space จะต้องห่อ `title` นั้นด้วยเครื่องหมายอ้างอิง ## generate -``` bash +```bash $ hexo generate ``` generate ไฟล์คงที่ -Option | Description ---- | --- -`-d`, `--deploy` | Deploy after generation finishes -`-w`, `--watch` | Watch file changes -`-b`, `--bail` | Raise an error if any unhandled exception is thrown during generation -`-f`, `--force` | Force regenerate +| Option | Description | +| ---------------- | --------------------------------------------------------------------- | +| `-d`, `--deploy` | Deploy after generation finishes | +| `-w`, `--watch` | Watch file changes | +| `-b`, `--bail` | Raise an error if any unhandled exception is thrown during generation | +| `-f`, `--force` | Force regenerate | ## publish -``` bash +```bash $ hexo publish [layout] <filename> ``` @@ -50,46 +51,46 @@ $ hexo publish [layout] <filename> ## server -``` bash +```bash $ hexo server ``` -เปิดเซร์ฟเวอร์ local เซร์ฟเวอร์ local นั้นจะเป็น `http://localhost:4000/` +เปิดเซร์ฟเวอร์ local เซร์ฟเวอร์ local นั้นจะเป็น `http://localhost:4000/` by default -Option | Description ---- | --- -`-p`, `--port` | Override default port -`-s`, `--static` | Only serve static files -`-l`, `--log` | Enable logger. Override logger format. +| Option | Description | +| ---------------- | -------------------------------------- | +| `-p`, `--port` | Override default port | +| `-s`, `--static` | Only serve static files | +| `-l`, `--log` | Enable logger. Override logger format. | ## deploy -``` bash +```bash $ hexo deploy ``` deploy เว็บไซต์ของคุณ -Option | Description ---- | --- -`-g`, `--generate` | Generate before deployment +| Option | Description | +| ------------------ | -------------------------- | +| `-g`, `--generate` | Generate before deployment | ## render -``` bash +```bash $ hexo render <file1> [file2] ... ``` render ไฟล์ต่างๆ -Option | Description ---- | --- -`-o`, `--output` | Output destination +| Option | Description | +| ---------------- | ------------------ | +| `-o`, `--output` | Output destination | ## migrate -``` bash +```bash $ hexo migrate <type> ``` @@ -97,7 +98,7 @@ $ hexo migrate <type> ## clean -``` bash +```bash $ hexo clean ``` @@ -105,7 +106,7 @@ $ hexo clean ## list -``` bash +```bash $ hexo list <type> ``` @@ -113,7 +114,7 @@ $ hexo list <type> ## version -``` bash +```bash $ hexo version ``` @@ -123,7 +124,7 @@ $ hexo version ### Safe mode -``` bash +```bash $ hexo --safe ``` @@ -131,16 +132,16 @@ $ hexo --safe ### Debug mode -``` bash +```bash $ hexo --debug ``` -log ข้อมูลละเอียดไปถึง terminal และ `debug.log` เมื่อเห็นข้อผิดพลาดใดๆอยู่ใน - log ไป[raise a GitHub issue](https://github.com/hexojs/hexo/issues/new)ได้ +log ข้อมูลละเอียดไปถึง terminal และ `debug.log` เมื่อเห็นข้อผิดพลาดใดๆอยู่ใน +log ไป[raise a GitHub issue](https://github.com/hexojs/hexo/issues/new)ได้ ### Silent mode -``` bash +```bash $ hexo --silent ``` @@ -148,7 +149,7 @@ silence ผลไปถึง terminal ### Customize config file path -``` bash +```bash $ hexo --config custom.yml ``` @@ -157,13 +158,13 @@ $ hexo --config custom.yml คุณต่องเขียนรายชื่อไฟล์พวกนี้อยู่ใน `_multiconfig.yml` และตัดแต่ละชื่อไฟล์ด้วยเครื่องหมายจุลภาค -``` bash +```bash $ hexo --config custom.yml,custom2.json ``` ### Display drafts -``` bash +```bash $ hexo --draft ``` @@ -171,7 +172,7 @@ $ hexo --draft ### Customize CWD -``` bash +```bash $ hexo --cwd /path/to/cwd ``` diff --git a/source/th/docs/configuration.md b/source/th/docs/configuration.md index 94ed4e8979..21535ae583 100644 --- a/source/th/docs/configuration.md +++ b/source/th/docs/configuration.md @@ -1,31 +1,32 @@ --- title: Configuration --- + คุณสามารถแก้ไขการตั้งค่าของเว็บไซต์ใน `_config.yml` หรือในไฟล์ [alternate config file](#Using-an-Alternate-Config) ### Site -Setting | Description ---- | --- -`title` | The title of your website -`subtitle` | The subtitle of your website -`description` | The description of your website -`keywords` | The keywords of your website. Supports multiple values. -`author` | Your name -`language` | The language of your website. Use a [2-lettter ISO-639-1 code](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). Default is `en`. -`timezone` | The timezone of your website. Hexo uses the setting on your computer by default. You can find the list of available timezones [here](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). Some examples are `America/New_York`, `Japan`, and `UTC`. +| Setting | Description | +| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `title` | The title of your website | +| `subtitle` | The subtitle of your website | +| `description` | The description of your website | +| `keywords` | The keywords of your website. Supports multiple values. | +| `author` | Your name | +| `language` | The language of your website. Use a [2-lettter ISO-639-1 code](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). Default is `en`. | +| `timezone` | The timezone of your website. Hexo uses the setting on your computer by default. You can find the list of available timezones [here](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). Some examples are `America/New_York`, `Japan`, and `UTC`. | ### URL -Setting | Description | Default ---- | --- | --- -`url` | The URL of your website, must starts with `http://` or `https://` | -`root` | The root directory of your website | `url's pathname` -`permalink` | The [permalink](permalinks.html) format of articles | `:year/:month/:day/:title/` -`permalink_defaults` | Default values of each segment in permalink | -`pretty_urls` | Rewrite the [`permalink`](variables.html) variables to pretty URLs | -`pretty_urls.trailing_index` | Trailing `index.html`, set to `false` to remove it | `true` -`pretty_urls.trailing_html` | Trailing `.html`, set to `false` to remove it (_does not apply to trailing `index.html`_) | `true` +| Setting | Description | Default | +| ---------------------------- | ----------------------------------------------------------------------------------------- | --------------------------- | +| `url` | The URL of your website, must starts with `http://` or `https://` | +| `root` | The root directory of your website | `url's pathname` | +| `permalink` | The [permalink](permalinks.html) format of articles | `:year/:month/:day/:title/` | +| `permalink_defaults` | Default values of each segment in permalink | +| `pretty_urls` | Rewrite the [`permalink`](variables.html) variables to pretty URLs | +| `pretty_urls.trailing_index` | Trailing `index.html`, set to `false` to remove it | `true` | +| `pretty_urls.trailing_html` | Trailing `.html`, set to `false` to remove it (_does not apply to trailing `index.html`_) | `true` | {% note info Website in subdirectory %} ถ้าเว็บไซต์ของคุณอยู่ใน subdirectory (เช่น `http://example.org/blog` ) @@ -34,53 +35,53 @@ Setting | Description | Default ### Directory -Setting | Description | Default ---- | --- | --- -`source_dir` | Source folder. Where your content is stored | `source` -`public_dir` | Public folder. Where the static site will be generated | `public` -`tag_dir` | Tag directory | `tags` -`archive_dir` | Archive directory | `archives` -`category_dir` | Category directory | `categories` -`code_dir` | Include code directory (subdirectory of `source_dir`) | `downloads/code` -`i18n_dir` | i18n directory | `:lang` -`skip_render` | Paths that will be copied to `public` raw, without being rendered. You can use [glob expressions](https://github.com/micromatch/micromatch#extended-globbing) for path matching.<br /><br />For example, `skip_render: mypage/**/*` will output `source/mypage/index.html` and `source/mypage/code.js` without altering them. | +| Setting | Description | Default | +| -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------- | +| `source_dir` | Source folder. Where your content is stored | `source` | +| `public_dir` | Public folder. Where the static site will be generated | `public` | +| `tag_dir` | Tag directory | `tags` | +| `archive_dir` | Archive directory | `archives` | +| `category_dir` | Category directory | `categories` | +| `code_dir` | Include code directory (subdirectory of `source_dir`) | `downloads/code` | +| `i18n_dir` | i18n directory | `:lang` | +| `skip_render` | Paths that will be copied to `public` raw, without being rendered. You can use [glob expressions](https://github.com/micromatch/micromatch#extended-globbing) for path matching.<br /><br />For example, `skip_render: mypage/**/*` will output `source/mypage/index.html` and `source/mypage/code.js` without altering them. | ### Writing -Setting | Description | Default ---- | --- | --- -`new_post_name` | The filename format for new posts | `:title.md` -`default_layout` | Default layout | `post` -`titlecase` | Transform titles into title case? | `false` -`external_link` | Open external links in a new tab? -`external_link.enable` | Open external links in a new tab? | `true` -`external_link.field` | Applies to the whole `site` or `post` only | `site` -`external_link.exclude` | Exclude hostname. Specify subdomain when applicable, including `www` | `[]` -`filename_case` | Transform filenames to `1` lower case; `2` upper case | `0` -`render_drafts` | Display drafts? | `false` -`post_asset_folder` | Enable the [Asset Folder](asset-folders.html)? | `false` -`relative_link` | Make links relative to the root folder? | `false` -`future` | Display future posts? | `true` -`highlight` | Code block syntax highlight settings, see [Highlight.js](/docs/syntax-highlight#Highlight-js) section for usage guide | -`prismjs` | Code block syntax highlight settings, see [PrismJS](/docs/syntax-highlight#PrismJS) section for usage guide | +| Setting | Description | Default | +| ----------------------- | --------------------------------------------------------------------------------------------------------------------- | ----------- | +| `new_post_name` | The filename format for new posts | `:title.md` | +| `default_layout` | Default layout | `post` | +| `titlecase` | Transform titles into title case? | `false` | +| `external_link` | Open external links in a new tab? | +| `external_link.enable` | Open external links in a new tab? | `true` | +| `external_link.field` | Applies to the whole `site` or `post` only | `site` | +| `external_link.exclude` | Exclude hostname. Specify subdomain when applicable, including `www` | `[]` | +| `filename_case` | Transform filenames to `1` lower case; `2` upper case | `0` | +| `render_drafts` | Display drafts? | `false` | +| `post_asset_folder` | Enable the [Asset Folder](asset-folders.html)? | `false` | +| `relative_link` | Make links relative to the root folder? | `false` | +| `future` | Display future posts? | `true` | +| `highlight` | Code block syntax highlight settings, see [Highlight.js](/docs/syntax-highlight#Highlight-js) section for usage guide | +| `prismjs` | Code block syntax highlight settings, see [PrismJS](/docs/syntax-highlight#PrismJS) section for usage guide | ### Category & Tag -Setting | Description | Default ---- | --- | --- -`default_category` | Default category | `uncategorized` -`category_map` | Category slugs | -`tag_map` | Tag slugs | +| Setting | Description | Default | +| ------------------ | ---------------- | --------------- | +| `default_category` | Default category | `uncategorized` | +| `category_map` | Category slugs | +| `tag_map` | Tag slugs | ### Date / Time format hexo ใช้ [Moment.js](http://momentjs.com/) มาจัดการวันเดือนปี -Setting | Description | Default ---- | --- | --- -`date_format` | Date format | `YYYY-MM-DD` -`time_format` | Time format | `HH:mm:ss` -`updated_option` | The [`updated`](/th/docs/variables#Page-Variables) value to used when not provided in the front-matter | `mtime` +| Setting | Description | Default | +| ---------------- | ------------------------------------------------------------------------------------------------------ | ------------ | +| `date_format` | Date format | `YYYY-MM-DD` | +| `time_format` | Time format | `HH:mm:ss` | +| `updated_option` | The [`updated`](/th/docs/variables#Page-Variables) value to used when not provided in the front-matter | `mtime` | {% note info updated_option %} `updated_option` controls the `updated` value when not provided in the front-matter: @@ -94,32 +95,32 @@ Setting | Description | Default ### Pagination -Setting | Description | Default ---- | --- | --- -`per_page` | The amount of posts displayed on a single page. `0` disables pagination | `10` -`pagination_dir` | Pagination directory | `page` +| Setting | Description | Default | +| ---------------- | ----------------------------------------------------------------------- | ------- | +| `per_page` | The amount of posts displayed on a single page. `0` disables pagination | `10` | +| `pagination_dir` | Pagination directory | `page` | ### Extensions -Setting | Description ---- | --- -`theme` | Theme name. `false` disables theming -`theme_config` | Theme configuration. Include any custom theme settings under this key to override theme defaults. -`deploy` | Deployment settings -`meta_generator` | [Meta generator](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta#Attributes) tag. `false` disables injection of the tag. +| Setting | Description | +| ---------------- | --------------------------------------------------------------------------------------------------------------------------------------- | +| `theme` | Theme name. `false` disables theming | +| `theme_config` | Theme configuration. Include any custom theme settings under this key to override theme defaults. | +| `deploy` | Deployment settings | +| `meta_generator` | [Meta generator](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta#Attributes) tag. `false` disables injection of the tag. | ### Include/Exclude Files or Folders ในไฟล์การตั้างค่า ตั้งค่า include/exclude ได้เพื่อทำให้ hexo -จัดการหรือละเลยไฟล์หรือ folder เฉพาะ +จัดการหรือละเลยไฟล์หรือ folder เฉพาะ `include` and `exclude` options only apply to the `source/` folder, whereas `ignore` option applies to all folders. -Setting | Description ---- | --- -`include` | Hexo by default ignores hidden files and folders, but setting this field will make Hexo process them -`exclude` | Hexo process will ignore files list under this field -`ignore` | Ignore files/folders +| Setting | Description | +| --------- | ---------------------------------------------------------------------------------------------------- | +| `include` | Hexo by default ignores hidden files and folders, but setting this field will make Hexo process them | +| `exclude` | Hexo process will ignore files list under this field | +| `ignore` | Ignore files/folders | ตัวอย่าง: @@ -170,7 +171,7 @@ path ของไฟล์การตั้งค่าจะถูกตั้ path นั้นสามารถชี้ถึงไฟล์การตั้งค่าท่ีมีรูปแบบเป็น YAML หรือ JSON หรือมีหมวกไฟล์ท่ีตัดรายชื่อด้วยเครื่องหมายจุลภาค -``` bash +```bash # use 'custom.yml' in place of '_config.yml' $ hexo server --config custom.yml @@ -185,7 +186,7 @@ $ hexo server --config custom.yml,custom2.json มีสิ่งท่ีต้องระวังคือ **no spaces are allowed in the list** ยกตัวอย่างเช่น ในตัวอย่างท่ีกล่าวข้างต้น ถ้่า `foo: bar` อยู่ในไฟล์ `custom -.yml` แต่ `"foo": "dinosaur"` อยู่ในไฟล์ `custom2.json` ไฟล์ +.yml` แต่ `"foo": "dinosaur"` อยู่ในไฟล์ `custom2.json` ไฟล์ `_multiconfig.yml` นั้นจะมีการตั้งค่าเป็น `foo: dinosaur` ### Alternate Theme Config @@ -204,7 +205,7 @@ theme: "my-theme" theme_config: bio: "My awesome bio" foo: - bar: 'a' + bar: "a" ``` ```yml @@ -219,11 +220,11 @@ Resulting in theme configuration: ```json { - bio: "My awesome bio", - logo: "a-cool-image.png", - foo: { - bar: "a", - baz: "b" + "bio": "My awesome bio", + "logo": "a-cool-image.png", + "foo": { + "bar": "a", + "baz": "b" } } ``` @@ -243,7 +244,7 @@ theme: "my-theme" # _config.my-theme.yml bio: "My awesome bio" foo: - bar: 'a' + bar: "a" ``` ```yml @@ -258,11 +259,11 @@ Resulting in theme configuration: ```json { - bio: "My awesome bio", - logo: "a-cool-image.png", - foo: { - bar: "a", - baz: "b" + "bio": "My awesome bio", + "logo": "a-cool-image.png", + "foo": { + "bar": "a", + "baz": "b" } } ``` diff --git a/source/th/docs/contributing.md b/source/th/docs/contributing.md index d38db32502..73e3e3c2f8 100644 --- a/source/th/docs/contributing.md +++ b/source/th/docs/contributing.md @@ -27,7 +27,7 @@ Also, Hexo has its own [ESLint config](https://github.com/hexojs/eslint-config-h 1. Fork [hexojs/hexo]. 2. Clone the repository to your computer and install dependencies. -``` bash +```bash $ git clone https://github.com/<username>/hexo.git $ cd hexo $ npm install @@ -36,7 +36,7 @@ $ git submodule update --init 3. Create a feature branch. -``` bash +```bash $ git checkout -b new_feature ``` @@ -54,7 +54,7 @@ $ git push origin new_feature - Don't modify version number in `package.json`. - Your pull request will only get merged when tests passed. Don't forget to run tests before submission. -``` bash +```bash $ npm test ``` @@ -71,7 +71,7 @@ documentation ของ hexo เป็น open source และคุณสา 1. Fork [hexojs/site] 2. Clone the repository to your computer and install dependencies. -``` bash +```bash $ npm install hexo-cli -g # If you don't have hexo-cli installed $ git clone https://github.com/<username>/site.git $ cd site @@ -80,7 +80,7 @@ $ npm install 3. Start editing the documentation. You can start the server for live previewing. -``` bash +```bash $ hexo server ``` diff --git a/source/th/docs/data-files.md b/source/th/docs/data-files.md index 3b9693912b..bc2db1cad2 100644 --- a/source/th/docs/data-files.md +++ b/source/th/docs/data-files.md @@ -1,16 +1,17 @@ --- title: Data Files --- + บางทีคุณอยากใช้ data ใน template ท่ีเข้าถึงโดยตรงไม่ได้ หรือคุณอยากเอา data -ไปใช้อีกในท่ีอื่นๆ ในกรณีเหล่านี้ hexo 3 จะแนะนำ **Data files** ใหม่ -ด้วยลักษณะนี้ hexo จะโหลดไฟล์ YAML หรือ JSON ใน folder `source/_data` +ไปใช้อีกในท่ีอื่นๆ ในกรณีเหล่านี้ hexo 3 จะแนะนำ **Data files** ใหม่ +ด้วยลักษณะนี้ hexo จะโหลดไฟล์ YAML หรือ JSON ใน folder `source/_data` และคุณจะใช้ data ในไฟล์ได้ในเว็บไซต์ของตน {% youtube CN31plHbI-w %} ยกตัวอย่างเช่น เพิ่ม `menu.yml` ใน folder `source/_data` -``` yaml +```yaml Home: / Gallery: /gallery/ Archives: /archives/ diff --git a/source/th/docs/front-matter.md b/source/th/docs/front-matter.md index 91a8b31617..b7aacfcb22 100644 --- a/source/th/docs/front-matter.md +++ b/source/th/docs/front-matter.md @@ -9,7 +9,7 @@ front-matter เป็น block ของ YAML หรือ JSON ท่ีอย **YAML** -``` yaml +```yaml --- title: Hello World date: 2013/7/13 20:46:25 @@ -18,7 +18,7 @@ date: 2013/7/13 20:46:25 **JSON** -``` json +```json "title": "Hello World", "date": "2013/7/13 20:46:25" ;;; @@ -26,23 +26,23 @@ date: 2013/7/13 20:46:25 ### Settings & Their Default Values -Setting | Description | Default ---- | --- | --- -`layout` | Layout | [`config.default_layout`](/th/docs/configuration#Writing) -`title` | Title | -`date` | Published date | File created date -`updated` | Updated date | File updated date -`comments` | Enables comment feature for the post | true -`tags` | Tags (Not available for pages) | -`categories` | Categories (Not available for pages) | -`permalink` | Overrides the default permalink of the post | -`excerpt` | Page excerpt in plain text. Use [this plugin](/docs/tag-plugins#Post-Excerpt) to format the text | -`disableNunjucks` | Disable rendering of Nunjucks tag `{{ }}`/`{% %}` and [tag plugins](/docs/tag-plugins) when enabled -`lang` | Set the language to override [auto-detection](/docs/internationalization#Path) | Inherited from `_config.yml` +| Setting | Description | Default | +| ----------------- | --------------------------------------------------------------------------------------------------- | --------------------------------------------------------- | +| `layout` | Layout | [`config.default_layout`](/th/docs/configuration#Writing) | +| `title` | Title | +| `date` | Published date | File created date | +| `updated` | Updated date | File updated date | +| `comments` | Enables comment feature for the post | true | +| `tags` | Tags (Not available for pages) | +| `categories` | Categories (Not available for pages) | +| `permalink` | Overrides the default permalink of the post | +| `excerpt` | Page excerpt in plain text. Use [this plugin](/docs/tag-plugins#Post-Excerpt) to format the text | +| `disableNunjucks` | Disable rendering of Nunjucks tag `{{ }}`/`{% %}` and [tag plugins](/docs/tag-plugins) when enabled | +| `lang` | Set the language to override [auto-detection](/docs/internationalization#Path) | Inherited from `_config.yml` | #### Layout -The default layout is `post`, in accordance to the value of [`default_layout`]((/docs/configuration#Writing)) setting in `_config.yml`. When the layout is disabled (`layout: false`) in an article, it will not be processed with a theme. However, it will still be rendered by any available renderer: if an article is written in Markdown and a Markdown renderer (like the default [hexo-renderer-marked](https://github.com/hexojs/hexo-renderer-marked)) is installed, it will be rendered to HTML. +The default layout is `post`, in accordance to the value of [`default_layout`](/docs/configuration#Writing) setting in `_config.yml`. When the layout is disabled (`layout: false`) in an article, it will not be processed with a theme. However, it will still be rendered by any available renderer: if an article is written in Markdown and a Markdown renderer (like the default [hexo-renderer-marked](https://github.com/hexojs/hexo-renderer-marked)) is installed, it will be rendered to HTML. [Tag plugins](/docs/tag-plugins) are always processed regardless of layout, unless disabled by the `disableNunjucks` setting or [renderer](/api/renderer#Disable-Nunjucks-tags). @@ -54,25 +54,25 @@ The default layout is `post`, in accordance to the value of [`default_layout`](( **ยกตัวอย่างเช่น:** -``` yaml +```yaml categories: -- Sports -- Baseball + - Sports + - Baseball tags: -- Injury -- Fight -- Shocking + - Injury + - Fight + - Shocking ``` ถ้าคุณอยากจัดหลายลำดับขั้นให้กับโพสต์ กรุณาเขียนรายชื่อของทุกลำดับขั้นให้ -ด้วยการกระทำอย่างนี้ hexo จะทำให้โพสต์อยู่ในทุกลำดับขั้นท่ีคัดเลือกมา +ด้วยการกระทำอย่างนี้ hexo จะทำให้โพสต์อยู่ในทุกลำดับขั้นท่ีคัดเลือกมา **ยกตัวอย่างเช่น:** -``` yaml +```yaml categories: -- [Sports, Baseball] -- [MLB, American League, Boston Red Sox] -- [MLB, American League, New York Yankees] -- Rivalries + - [Sports, Baseball] + - [MLB, American League, Boston Red Sox] + - [MLB, American League, New York Yankees] + - Rivalries ``` diff --git a/source/th/docs/generating.md b/source/th/docs/generating.md index 0dbbb0f3b1..9c8e69f8fc 100644 --- a/source/th/docs/generating.md +++ b/source/th/docs/generating.md @@ -1,9 +1,10 @@ --- title: Generating --- + การ generate ไฟล์คงท่ีใน hexo จะค่อนข้างรวดเร็วและง่าย -``` bash +```bash $ hexo generate ``` @@ -14,7 +15,7 @@ $ hexo generate hexo จะเฝ้าดูการเปลี่ยนแปลงของไฟล์และ generate ไฟล์ ทันที เฝ้าดูการเปลี่ยนแปลงของไฟล์นั้นจะเป็นการเปรียนเทียบ SHA1 checksum ของไฟล์ -``` bash +```bash $ hexo generate --watch ``` @@ -22,7 +23,7 @@ $ hexo generate --watch คำสั่งสองบรรทัดต่อไปจะมีการปฏิบัติเหมือนกันสำหรับการ deploy หลังการ generate ไฟล์ -``` bash +```bash $ hexo generate --deploy $ hexo deploy --generate ``` diff --git a/source/th/docs/github-pages.md b/source/th/docs/github-pages.md index 131ccabc1d..a2d5fcfc39 100755 --- a/source/th/docs/github-pages.md +++ b/source/th/docs/github-pages.md @@ -4,14 +4,14 @@ title: GitHub Pages In this tutorial, we use [Travis CI](https://travis-ci.com/) to deploy Github Pages. It is free for open source repository, meaning your repository's `master` branch has to be public. Please skip to the [Private repository](#Private-repository) section if you prefer to keep the repo private, or prefer not to upload your source folder to GitHub. -1. Create a repo named <b>*username*.github.io</b>, where username is your username on GitHub. If you have already uploaded to other repo, rename the repo instead. +1. Create a repo named <b>_username_.github.io</b>, where username is your username on GitHub. If you have already uploaded to other repo, rename the repo instead. 2. Push the files of your Hexo folder to the repository. The `public/` folder is not (and should not be) uploaded by default, make sure the `.gitignore` file contains `public/` line. The folder structure should be roughly similar to [this repo](https://github.com/hexojs/hexo-starter), without the `.gitmodules` file. 3. Add [Travis CI](https://github.com/marketplace/travis-ci) to your account. 4. Go to [Applications settings](https://github.com/settings/installations), configure Travis CI to have access to the repo. 5. You'll be redirected to Travis page. 6. On a new tab, generate a [new token](https://github.com/settings/tokens) with **repo** scopes. Note down the token value. 7. On the Travis page, go to your repo's setting. Under **Environment Variables**, put **GH_TOKEN** as name and paste the token onto value. Click Add to save it. -8. Add `.travis.yml` file to your repo (alongside _config.yml & package.json) with the following content: +8. Add `.travis.yml` file to your repo (alongside \_config.yml & package.json) with the following content: ```yml sudo: false @@ -36,26 +36,26 @@ deploy: 9. Once Travis CI finish the deployment, the generated pages can be found in the `gh-pages` branch of your repository 10. In your GitHub repo's setting, navigate to "GitHub Pages" section and change Source to **gh-pages branch**. -11. Check the webpage at *username*.github.io. +11. Check the webpage at _username_.github.io. ## Project page If you prefer to have a project page on GitHub: -1. Navigate to your repo on GitHub. Go to the **Settings** tab. Change the **Repository name** so your blog is available at <b>username.github.io/*repository*</b>, **repository** can be any name, like *blog* or *hexo*. -2. Edit your **_config.yml**, change the `root:` value to the `/<repository>/` (must starts and ends with a slash, without the brackets). +1. Navigate to your repo on GitHub. Go to the **Settings** tab. Change the **Repository name** so your blog is available at <b>username.github.io/_repository_</b>, **repository** can be any name, like _blog_ or _hexo_. +2. Edit your **\_config.yml**, change the `root:` value to the `/<repository>/` (must starts and ends with a slash, without the brackets). 3. Commit and push. ## Private repository This section only applies to private repo. -1. Create a repo named <b>*username*.github.io</b>, where username is your username on GitHub. If you have already uploaded to other repo, rename the repo instead. _(Skip to step 3 if you prefer not to upload your source folder to GitHub at all)_ +1. Create a repo named <b>_username_.github.io</b>, where username is your username on GitHub. If you have already uploaded to other repo, rename the repo instead. _(Skip to step 3 if you prefer not to upload your source folder to GitHub at all)_ 2. Push the files of your Hexo folder to the repository. The `public/` folder is not (and should not be) uploaded by default, make sure the `.gitignore` file contains `public/` line. The folder structure should be roughly similar to [this repo](https://github.com/hexojs/hexo-starter), without the `.gitmodules` file. 3. Run `hexo generate` and copy the `public/` folder to somewhere else (in your workstation). 4. Create a new `gh-pages` git branch from your Hexo folder, we recommend creating an orphan branch (to create a new branch without commit history): -``` bash +```bash $ git checkout --orphan gh-pages ``` @@ -63,7 +63,7 @@ $ git checkout --orphan gh-pages 6. Move the _content_ of the `public/` folder back. 7. Commit and push the gh-pages branch. -``` bash +```bash $ git add . $ git commit -a -m "Initial commit" $ git push origin gh-pages @@ -73,7 +73,7 @@ $ git push origin gh-pages 9. Check the webpage at your-username.github.io. 10. To navigate back to your source folder, -``` bash +```bash $ git checkout master ``` diff --git a/source/th/docs/gitlab-pages.md b/source/th/docs/gitlab-pages.md index 7b5ce4d6c9..2d4384d923 100644 --- a/source/th/docs/gitlab-pages.md +++ b/source/th/docs/gitlab-pages.md @@ -2,12 +2,12 @@ title: GitLab Pages --- -1. Create a new repository named <b>*username*.gitlab.io</b>, where username is your username on GitLab. If you have already uploaded to other repo, rename the repo instead. +1. Create a new repository named <b>_username_.gitlab.io</b>, where username is your username on GitLab. If you have already uploaded to other repo, rename the repo instead. 2. Enable Shared Runners via `Settings -> CI / CD -> Shared Runners`. 3. Push the files of your Hexo folder to the repository. The `public/` folder is not (and should not be) uploaded by default, make sure the `.gitignore` file contains `public/` line. The folder structure should be roughly similar to [this repo](https://gitlab.com/pages/hexo). -4. Add `.gitlab-ci.yml` file to your repo (alongside _config.yml & package.json) with the following content: +4. Add `.gitlab-ci.yml` file to your repo (alongside \_config.yml & package.json) with the following content: -``` yml +```yml image: node:10-alpine # use nodejs v10 LTS cache: paths: @@ -27,15 +27,15 @@ pages: - master ``` -5. *username*.gitlab.io should be up and running, once GitLab CI finishes the deployment job, +5. _username_.gitlab.io should be up and running, once GitLab CI finishes the deployment job, 6. (Optional) If you wish to inspect the generated site assets (html, css, js, etc), they can be found in the [job artifact](https://docs.gitlab.com/ee/user/project/pipelines/job_artifacts.html). ## Project page If you prefer to have a project page on GitLab: -1. Go to `Settings -> General -> Advanced -> Change path`. Change the value to a name, so the website is available at <b>username.gitlab.io/*name*</b>. It can be any name, like *blog* or *hexo*. -2. Edit **_config.yml**, change the `root:` value from `""` to `"name"`. +1. Go to `Settings -> General -> Advanced -> Change path`. Change the value to a name, so the website is available at <b>username.gitlab.io/_name_</b>. It can be any name, like _blog_ or _hexo_. +2. Edit **\_config.yml**, change the `root:` value from `""` to `"name"`. 3. Commit and push. ## Useful links diff --git a/source/th/docs/helpers.md b/source/th/docs/helpers.md index 420e351d5e..375574e59e 100644 --- a/source/th/docs/helpers.md +++ b/source/th/docs/helpers.md @@ -12,10 +12,10 @@ helper จะถูกใช้ใน template เพื่อช่วยเส ### url_for -ส่งกลับ url ท่ีมี root path ตั้งขึ้นไว้ คุณต้องใช้ helper นี้แทน `config +ส่งกลับ url ท่ีมี root path ตั้งขึ้นไว้ คุณต้องใช้ helper นี้แทน `config .root + path` ของ hexo 2.7 -``` js +```js <%- url_for(path) %> ``` @@ -23,7 +23,7 @@ helper จะถูกใช้ใน template เพื่อช่วยเส ส่งกลับ relative URL จาก `from` ไปเป็น `to` -``` js +```js <%- relative_url(from, to) %> ``` @@ -31,17 +31,17 @@ helper จะถูกใช้ใน template เพื่อช่วยเส เสียบรูปภาพ Gravatar เข้า: -ถ้าคุณไม่ได้ป่งชี้ parameter ของ [options] ให้ชัดเจน จะมีการตั้งค่าให้ by -default แล้วคุณก็สามารถตั้งค่า option ด้วยตนเอง ถ้าคุณตั้งค่านี้เป็น object +ถ้าคุณไม่ได้ป่งชี้ parameter ของ [options] ให้ชัดเจน จะมีการตั้งค่าให้ by +default แล้วคุณก็สามารถตั้งค่า option ด้วยตนเอง ถ้าคุณตั้งค่านี้เป็น object object นั้นจะถูกเปลี่ยนไปเป็น query string -``` js +```js <%- gravatar(email, [options]) %> ``` **ยกตัวอย่างเช่น:** -``` js +```js <%- gravatar('a@abc.com') %> // https://www.gravatar.com/avatar/b9b00e66c6b8a70f88c73cb6bdb06787 @@ -56,19 +56,19 @@ object นั้นจะถูกเปลี่ยนไปเป็น query ### css -โหลดไฟล์ CSS `path` นั้นเป็น array หรือ string ได้ ถ้า `path` นั้นไม่มี `/` +โหลดไฟล์ CSS `path` นั้นเป็น array หรือ string ได้ ถ้า `path` นั้นไม่มี `/` หรือ protocol ใดๆ เป็นคำนำหน้า มันจะมี root URL เป็นคำนำหน้า -ถ้าคุณไม่ได้เพิ่ม extension ท่ีเป็น `.css` หลัง `path` extension +ถ้าคุณไม่ได้เพิ่ม extension ท่ีเป็น `.css` หลัง `path` extension นั้นจะถูกเพิ่มให้ไฟล์โดยอัตโนมัติ Use object type for custom attributes. -``` js +```js <%- css(path, ...) %> ``` **ยกตัวอย่างเช่น:** -``` js +```js <%- css('style.css') %> // <link rel="stylesheet" href="/style.css"> @@ -86,19 +86,19 @@ Use object type for custom attributes. ### js -โหลดไฟล์ JavaScript `path` นั้นเป็น array หรือ string ได้ ถ้า `path` +โหลดไฟล์ JavaScript `path` นั้นเป็น array หรือ string ได้ ถ้า `path` นั้นไม่มี `/` หรือ protocol ใดๆ เป็นคำนำหน้า มันจะมี root URL เป็นคำนำหน้า -ถ้าคุณไม่ได้เพิ่ม extension ท่ีเป็น `.js` หลัง `path` extension +ถ้าคุณไม่ได้เพิ่ม extension ท่ีเป็น `.js` หลัง `path` extension นั้นจะถูกเพิ่มให้ไฟล์โดยอัตโนมัติ Use object type for custom attributes. -``` js +```js <%- js(path, ...) %> ``` **ยกตัวอย่างเช่น:** -``` js +```js <%- js('script.js') %> // <script src="/script.js"></script> @@ -118,19 +118,19 @@ Use object type for custom attributes. เสียบลิงก์เข้า: -``` js +```js <%- link_to(path, [text], [options]) %> ``` -Option | Description | Default ---- | --- | --- -`external` | Opens the link in a new tab | false -`class` | Class name | -`id` | ID | +| Option | Description | Default | +| ---------- | --------------------------- | ------- | +| `external` | Opens the link in a new tab | false | +| `class` | Class name | +| `id` | ID | **ยกตัวอย่างเช่น:** -``` js +```js <%- link_to('http://www.google.com') %> // <a href="http://www.google.com" title="http://www.google.com">http://www.google.com</a> @@ -145,22 +145,22 @@ Option | Description | Default เสียบลิงก์ของเมล์เข้า: -``` js +```js <%- mail_to(path, [text], [options]) %> ``` -Option | Description ---- | --- -`class` | Class name -`id` | ID -`subject` | Mail subject -`cc` | CC -`bcc` | BCC -`body` | Mail content +| Option | Description | +| --------- | ------------ | +| `class` | Class name | +| `id` | ID | +| `subject` | Mail subject | +| `cc` | CC | +| `bcc` | BCC | +| `body` | Mail content | **ยกตัวอย่างเช่น:** -``` js +```js <%- mail_to('a@abc.com') %> // <a href="mailto:a@abc.com" title="a@abc.com">a@abc.com</a> @@ -172,23 +172,23 @@ Option | Description เสียบรูปภาพเข้า: -``` js +```js <%- image_tag(path, [options]) %> ``` -Option | Description ---- | --- -`alt` | Alternative text of the image -`class` | Class name -`id` | ID -`width` | Image width -`height` | Image height +| Option | Description | +| -------- | ----------------------------- | +| `alt` | Alternative text of the image | +| `class` | Class name | +| `id` | ID | +| `width` | Image width | +| `height` | Image height | ### favicon_tag เสียบ favicon เข้า: -``` js +```js <%- favicon_tag(path) %> ``` @@ -196,18 +196,18 @@ Option | Description เสียบลิงก์ฟีดเข้า: -``` js +```js <%- feed_tag(path, [options]) %> ``` -Option | Description | Default ---- | --- | --- -`title` | Feed title | `config.title` -`type` | Feed type | +| Option | Description | Default | +| ------- | ----------- | -------------- | +| `title` | Feed title | `config.title` | +| `type` | Feed type | **Examples:** -``` js +```js <%- feed_tag('atom.xml') %> // <link rel="alternate" href="/atom.xml" title="Hexo" type="application/atom+xml"> @@ -223,10 +223,10 @@ Option | Description | Default ### is_current -ตรวจได้ว่า `path` นั้นเหมาะกับ URL ของเพจปัจจุบันหรือไม่ คุณใช้ตัวเลือก +ตรวจได้ว่า `path` นั้นเหมาะกับ URL ของเพจปัจจุบันหรือไม่ คุณใช้ตัวเลือก `strict` ไปเปิด strict matching ได้ -``` js +```js <%- is_current(path, [strict]) %> ``` @@ -234,7 +234,7 @@ Option | Description | Default ตรวจได้ว่าเพจปัจจุบันเป็นหน้าหลักหรือไม่ -``` js +```js <%- is_home() %> ``` @@ -242,7 +242,7 @@ Option | Description | Default ตรวจได้ว่าเพจปัจจุบันเป็นโพสต์หรือไม่ -``` js +```js <%- is_post() %> ``` @@ -250,7 +250,7 @@ Option | Description | Default ตรวจได้ว่าเพจปัจจุบันเป็นเพจ archive หรือไม่ -``` js +```js <%- is_archive() %> ``` @@ -258,7 +258,7 @@ Option | Description | Default ตรวจได้ว่าเพจปัจจุบันเป็นเพจ archive ต่อปีหรือไม่ -``` js +```js <%- is_year() %> ``` @@ -266,17 +266,17 @@ Option | Description | Default ตรวจได้ว่าเพจปัจจุบันเป็นเพจ archive ต่อเดือนหรือไม่ -``` js +```js <%- is_month() %> ``` ### is_category ตรวจได้ว่าเพจปัจจุบันเป็นเพจ category หรือไม่ -ถ้า parameter นั้นเป็น string จะตรวจได้ว่าเพจปัจจุบันอยู่ใน category +ถ้า parameter นั้นเป็น string จะตรวจได้ว่าเพจปัจจุบันอยู่ใน category นั้นหรือไม่ -``` js +```js <%- is_category() %> <%- is_category('hobby') %> ``` @@ -286,7 +286,7 @@ Option | Description | Default ตรวจได้ว่าเพจปัจจุบันเป็นเพจแท็กหรือไม่ ถ้า parameter นั้นเป็น string จะตรวจได้ว่าเพจปัจจุบันเหมาะกับแท็กนั้นหรือไม่ -``` js +```js <%- is_tag() %> <%- is_tag('hobby') %> ``` @@ -297,7 +297,7 @@ Option | Description | Default ลบ space ท่ีอยู่ข้่างต้นหรือระหว่างตัวอักษรต่างๆของ string -``` js +```js <%- trim(string) %> ``` @@ -305,13 +305,13 @@ Option | Description | Default ลบแท็ก HTML ทั้งหมดของ string -``` js +```js <%- strip_html(string) %> ``` **ยกตัวอย่างเช่น:** -``` js +```js <%- strip_html('It\'s not <b>important</b> anymore!') %> // It's not important anymore! ``` @@ -320,13 +320,13 @@ Option | Description | Default เปลี่ยน string ไปเป็นตัวอักษรท่ีถูกต้อง -``` js +```js <%- titlecase(string) %> ``` **ยกตัวอย่างเช่น:** -``` js +```js <%- titlecase('this is an apple') %> # This is an Apple ``` @@ -335,13 +335,13 @@ Option | Description | Default render string ด้วย Markdown -``` js +```js <%- markdown(str) %> ``` **ยกตัวอย่างเช่น:** -``` js +```js <%- markdown('make me **strong**') %> // make me <strong>strong</strong> ``` @@ -350,13 +350,13 @@ render string ด้วย Markdown Renders a string. -``` js +```js <%- render(str, engine, [options]) %> ``` **Examples:** -``` js +```js <%- render('p(class="example") Test', 'pug'); %> // <p class="example">Test</p> ``` @@ -365,16 +365,16 @@ See [Rendering](https://hexo.io/th/api/rendering) for more details. ### word_wrap -ทุกบรรทัดของ text จะไม่ยาวเกิน `length` ค่า `length` นั้นจะเป็น 80 ตัวอักษร - by default +ทุกบรรทัดของ text จะไม่ยาวเกิน `length` ค่า `length` นั้นจะเป็น 80 ตัวอักษร +by default -``` js +```js <%- word_wrap(str, [length]) %> ``` **ยกตัวอย่างเช่น:** -``` js +```js <%- word_wrap('Once upon a time', 8) %> // Once upon\n a time ``` @@ -384,13 +384,13 @@ See [Rendering](https://hexo.io/th/api/rendering) for more details. ตัด text ให้สั้นตามการตั้งค่าของ `length` การตั้งค่า `length` default เป็นตัวอักษร 30 ตัว -``` js +```js <%- truncate(text, [options]) %> ``` **ยกตัวอย่างเช่น:** -``` js +```js <%- truncate('Once upon a time in a world far far away', {length: 17}) %> // Once upon a ti... @@ -405,13 +405,13 @@ See [Rendering](https://hexo.io/th/api/rendering) for more details. Escapes HTML entities in a string. -``` js +```js <%- escape_html(str) %> ``` **Examples:** -``` js +```js <%- escape_html('<p>Hello "world".</p>') %> // <p>Hello "world".</p> ``` @@ -422,27 +422,27 @@ Escapes HTML entities in a string. โหลดไฟล์ template อื่นๆ คุณสามารถตั้งค่า local variable ใน `locals` -``` js +```js <%- partial(layout, [locals], [options]) %> ``` -Option | Description | Default ---- | --- | --- -`cache` | Cache contents (Use fragment cache) | `false` -`only` | Strict local variables. Only use variables set in `locals` in templates. | `false` +| Option | Description | Default | +| ------- | ------------------------------------------------------------------------ | ------- | +| `cache` | Cache contents (Use fragment cache) | `false` | +| `only` | Strict local variables. Only use variables set in `locals` in templates. | `false` | ### fragment_cache cache เนื้อหาอยู่ใน fragment มันจะบันทึกเนื้อหาอยู่ใน fragment และ cache นั้นจะทำให้ request ท่ีเกี่ยวข้องนั้นมีการตอบรับเร็วขึ้น -``` js +```js <%- fragment_cache(id, fn); ``` **ยกตัวอย่างเช่น:** -``` js +```js <%- fragment_cache('header', function(){ return '<header></header>'; }) %> @@ -455,15 +455,15 @@ cache เนื้อหาอยู่ใน fragment มันจะบัน เสียบวันเดือนปีท่ีได้จัดรูปแบบแล้วเข้า: `date` นั้นจะเป็น unix time, ISO string, date object, หรือ [Moment.js] object - ได้ `format` นั้นถูกตั้งค่าเป็น `date_format` อยู่แล้ว by default +ได้ `format` นั้นถูกตั้งค่าเป็น `date_format` อยู่แล้ว by default -``` js +```js <%- date(date, [format]) %> ``` **ยกตัวอย่างเช่น:** -``` js +```js <%- date(Date.now()) %> // 2013-01-01 @@ -476,15 +476,15 @@ cache เนื้อหาอยู่ใน fragment มันจะบัน เสียบวันเดือนปีเข้าในรูปแบบ XML : `date` นั้นจะเป็น unix time, ISO string, date object, หรือ [Moment.js] object - ได้ +ได้ -``` js +```js <%- date_xml(date) %> ``` **ยกตัวอย่างเช่น:** -``` js +```js <%- date_xml(Date.now()) %> // 2013-01-01T00:00:00.000Z ``` @@ -496,13 +496,13 @@ cache เนื้อหาอยู่ใน fragment มันจะบัน `date` นั้นเป็น unix time, ISO string, date object, หรือ [Moment.js] object ได้ `format` นั้นถูกตั้งค่าเป็น `time_format` อยู่แล้ว by default -``` js +```js <%- time(date, [format]) %> ``` **ยกตัวอย่างเช่น:** -``` js +```js <%- time(Date.now()) %> // 13:05:12 @@ -517,13 +517,13 @@ cache เนื้อหาอยู่ใน fragment มันจะบัน `date` นั้นเป็น unix time, ISO string, date object, หรือ [Moment.js] object ได้ `format` นั้นถูกตั้งค่าเป็น `date_format + time_format` อยู่แล้ว by default -``` js +```js <%- full_date(date, [format]) %> ``` **ยกตัวอย่างเช่น:** -``` js +```js <%- full_date(new Date()) %> // Jan 1, 2013 0:00:00 @@ -541,31 +541,31 @@ cache เนื้อหาอยู่ใน fragment มันจะบัน เสียบรายชื่อของ category ทั้งหมดเข้า: -``` js +```js <%- list_categories([options]) %> ``` -Option | Description | Default ---- | --- | --- -`orderby` | Order of categories | name -`order` | Sort of order. `1`, `asc` for ascending; `-1`, `desc` for descending | 1 -`show_count` | Display the number of posts for each category | true -`style` | Style to display the category list. `list` displays categories in an unordered list. | list -`separator` | Separator between categories. (Only works if `style` is not `list`) | , -`depth` | Levels of categories to be displayed. `0` displays all categories and child categories; `-1` is similar to `0` but displayed in flat; `1` displays only top level categories. | 0 -`class` | Class name of tag list (string) or customize each tag's class (object, see below). | tag -`transform` | The function that changes the display of category name. | -`suffix` | Add a suffix to link. | None +| Option | Description | Default | +| ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| `orderby` | Order of categories | name | +| `order` | Sort of order. `1`, `asc` for ascending; `-1`, `desc` for descending | 1 | +| `show_count` | Display the number of posts for each category | true | +| `style` | Style to display the category list. `list` displays categories in an unordered list. | list | +| `separator` | Separator between categories. (Only works if `style` is not `list`) | , | +| `depth` | Levels of categories to be displayed. `0` displays all categories and child categories; `-1` is similar to `0` but displayed in flat; `1` displays only top level categories. | 0 | +| `class` | Class name of tag list (string) or customize each tag's class (object, see below). | tag | +| `transform` | The function that changes the display of category name. | +| `suffix` | Add a suffix to link. | None | Class advanced customization: -Option | Description | Default ---- | --- | --- -`class.ul` | `<ul>` class name (only for style `list`) | `tag-list` (list style) -`class.li` | `<li>` class name (only for style `list`) | `tag-list-item` (list style) -`class.a` | `<a>` class name | `tag-list-link` (list style) `tag-link` (normal style) -`class.label` | `<span>` class name where the tag label is stored (only for normal style, when `class.label` is set the label is put in a `<span>`) | `tag-label` (normal style) -`class.count` | `<span>` class name where the tag counter is stored (only when `show_count` is `true`) | `tag-list-count` (list style) `tag-count` (normal style) +| Option | Description | Default | +| ------------- | ----------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------- | +| `class.ul` | `<ul>` class name (only for style `list`) | `tag-list` (list style) | +| `class.li` | `<li>` class name (only for style `list`) | `tag-list-item` (list style) | +| `class.a` | `<a>` class name | `tag-list-link` (list style) `tag-link` (normal style) | +| `class.label` | `<span>` class name where the tag label is stored (only for normal style, when `class.label` is set the label is put in a `<span>`) | `tag-label` (normal style) | +| `class.count` | `<span>` class name where the tag counter is stored (only when `show_count` is `true`) | `tag-list-count` (list style) `tag-count` (normal style) | Examples: @@ -580,30 +580,30 @@ Examples: เสียบรายชื่อของแท็กทั้งหมดเข้า: -``` js +```js <%- list_tags([options]) %> ``` -Option | Description | Default ---- | --- | --- -`orderby` | Order of categories | name -`order` | Sort of order. `1`, `asc` for ascending; `-1`, `desc` for descending | 1 -`show_count` | Display the number of posts for each tag | true -`style` | Style to display the tag list. `list` displays tags in an unordered list. | list -`separator` | Separator between categories. (Only works if `style` is not `list`) | , -`class` | Class name of tag list. | tag -`transform` | The function that changes the display of tag name. | -`amount` | The number of tags to display (0 = unlimited) | 0 -`suffix` | Add a suffix to link. | None +| Option | Description | Default | +| ------------ | ------------------------------------------------------------------------- | ------- | +| `orderby` | Order of categories | name | +| `order` | Sort of order. `1`, `asc` for ascending; `-1`, `desc` for descending | 1 | +| `show_count` | Display the number of posts for each tag | true | +| `style` | Style to display the tag list. `list` displays tags in an unordered list. | list | +| `separator` | Separator between categories. (Only works if `style` is not `list`) | , | +| `class` | Class name of tag list. | tag | +| `transform` | The function that changes the display of tag name. | +| `amount` | The number of tags to display (0 = unlimited) | 0 | +| `suffix` | Add a suffix to link. | None | Class advanced customization: -Option | Description | Default ---- | --- | --- -`class.ul` | `<ul>` class name (only for style `list`) | `tag-list` (list style) -`class.li` | `<li>` class name (only for style `list`) | `tag-list-item` (list style) -`class.a` | `<a>` class name | `tag-list-link` (list style) `tag-link` (normal style) -`class.count` | `<span>` class name where the tag counter is stored (only when `show_count` is `true`) | `tag-list-count` (list style) `tag-count` (normal style) +| Option | Description | Default | +| ------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------- | +| `class.ul` | `<ul>` class name (only for style `list`) | `tag-list` (list style) | +| `class.li` | `<li>` class name (only for style `list`) | `tag-list-item` (list style) | +| `class.a` | `<a>` class name | `tag-list-link` (list style) `tag-link` (normal style) | +| `class.count` | `<span>` class name where the tag counter is stored (only when `show_count` is `true`) | `tag-list-count` (list style) `tag-count` (normal style) | Examples: @@ -618,60 +618,60 @@ Examples: เสียบรายชื่อ archive เข้า: -``` js +```js <%- list_archives([options]) %> ``` -Option | Description | Default ---- | --- | --- -`type` | Type. This value can be `yearly` or `monthly`. | monthly -`order` | Sort of order. `1`, `asc` for ascending; `-1`, `desc` for descending | 1 -`show_count` | Display the number of posts for each archive | true -`format` | Date format | MMMM YYYY -`style` | Style to display the archive list. `list` displays archives in an unordered list. | list -`separator` | Separator between archives. (Only works if `style` is not `list`) | , -`class` | Class name of archive list. | archive -`transform` | The function that changes the display of archive name. | +| Option | Description | Default | +| ------------ | --------------------------------------------------------------------------------- | --------- | +| `type` | Type. This value can be `yearly` or `monthly`. | monthly | +| `order` | Sort of order. `1`, `asc` for ascending; `-1`, `desc` for descending | 1 | +| `show_count` | Display the number of posts for each archive | true | +| `format` | Date format | MMMM YYYY | +| `style` | Style to display the archive list. `list` displays archives in an unordered list. | list | +| `separator` | Separator between archives. (Only works if `style` is not `list`) | , | +| `class` | Class name of archive list. | archive | +| `transform` | The function that changes the display of archive name. | ### list_posts เสียบรายชื่อโพสต์เข้า: -``` js +```js <%- list_posts([options]) %> ``` -Option | Description | Default ---- | --- | --- -`orderby` | Order of posts | date -`order` | Sort of order. `1`, `asc` for ascending; `-1`, `desc` for descending | 1 -`style` | Style to display the post list. `list` displays posts in an unordered list. | list -`separator` | Separator between posts. (Only works if `style` is not `list`) | , -`class` | Class name of post list. | post -`amount` | The number of posts to display (0 = unlimited) | 6 -`transform` | The function that changes the display of post name. | +| Option | Description | Default | +| ----------- | --------------------------------------------------------------------------- | ------- | +| `orderby` | Order of posts | date | +| `order` | Sort of order. `1`, `asc` for ascending; `-1`, `desc` for descending | 1 | +| `style` | Style to display the post list. `list` displays posts in an unordered list. | list | +| `separator` | Separator between posts. (Only works if `style` is not `list`) | , | +| `class` | Class name of post list. | post | +| `amount` | The number of posts to display (0 = unlimited) | 6 | +| `transform` | The function that changes the display of post name. | ### tagcloud เสียบ tag cloud เข้า: -``` js +```js <%- tagcloud([tags], [options]) %> ``` -Option | Description | Default ---- | --- | --- -`min_font` | Minimal font size | 10 -`max_font` | Maximum font size | 20 -`unit` | Unit of font size | px -`amount` | Total amount of tags | 40 -`orderby` | Order of tags | name -`order` | Sort order. `1`, `sac` as ascending; `-1`, `desc` as descending | 1 -`color` | Colorizes the tag cloud | false -`start_color` | Start color. You can use hex (`#b700ff`), rgba (`rgba(183, 0, 255, 1)`), hsla (`hsla(283, 100%, 50%, 1)`) or [color keywords]. This option only works when `color` is true. | -`end_color` | End color. You can use hex (`#b700ff`), rgba (`rgba(183, 0, 255, 1)`), hsla (`hsla(283, 100%, 50%, 1)`) or [color keywords]. This option only works when `color` is true. | -`class` | Class name prefix of tags -`level` | The number of different class names. This option only works when `class` is set. | 10 +| Option | Description | Default | +| ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| `min_font` | Minimal font size | 10 | +| `max_font` | Maximum font size | 20 | +| `unit` | Unit of font size | px | +| `amount` | Total amount of tags | 40 | +| `orderby` | Order of tags | name | +| `order` | Sort order. `1`, `sac` as ascending; `-1`, `desc` as descending | 1 | +| `color` | Colorizes the tag cloud | false | +| `start_color` | Start color. You can use hex (`#b700ff`), rgba (`rgba(183, 0, 255, 1)`), hsla (`hsla(283, 100%, 50%, 1)`) or [color keywords]. This option only works when `color` is true. | +| `end_color` | End color. You can use hex (`#b700ff`), rgba (`rgba(183, 0, 255, 1)`), hsla (`hsla(283, 100%, 50%, 1)`) or [color keywords]. This option only works when `color` is true. | +| `class` | Class name prefix of tags | +| `level` | The number of different class names. This option only works when `class` is set. | 10 | ## Miscellaneous @@ -679,35 +679,35 @@ Option | Description | Default เสียบ paginator เข้า: -``` js +```js <%- paginator(options) %> ``` -Option | Description | Default ---- | --- | --- -`base` | Base URL | / -`format` | URL format | page/%d/ -`total` | The number of pages | 1 -`current` | Current page number | 0 -`prev_text` | The link text of previous page. Works only if `prev_next` is set to true. | Prev -`next_text` | The link text of next page. Works only if `prev_next` is set to true. | Next -`space` | The space text | &hellp; -`prev_next` | Display previous and next links | true -`end_size` | The number of pages displayed on the start and the end side | 1 -`mid_size` | The number of pages displayed between current page, but not including current page | 2 -`show_all` | Display all pages. If this is set true, `end_size` and `mid_size` will not works. | false -`escape` | Escape HTML tags | true +| Option | Description | Default | +| ----------- | ---------------------------------------------------------------------------------- | -------- | +| `base` | Base URL | / | +| `format` | URL format | page/%d/ | +| `total` | The number of pages | 1 | +| `current` | Current page number | 0 | +| `prev_text` | The link text of previous page. Works only if `prev_next` is set to true. | Prev | +| `next_text` | The link text of next page. Works only if `prev_next` is set to true. | Next | +| `space` | The space text | &hellp; | +| `prev_next` | Display previous and next links | true | +| `end_size` | The number of pages displayed on the start and the end side | 1 | +| `mid_size` | The number of pages displayed between current page, but not including current page | 2 | +| `show_all` | Display all pages. If this is set true, `end_size` and `mid_size` will not works. | false | +| `escape` | Escape HTML tags | true | **Examples:** -``` js +```js <%- paginator({ prev_text: '<', next_text: '>' }) %> ``` -``` html +```html <!-- Rendered as --> <a href="/1/"><</a> <a href="/1/">1</a> @@ -716,7 +716,7 @@ Option | Description | Default <a href="/3/">></a> ``` -``` js +```js <%- paginator({ prev_text: '<i class="fa fa-angle-left"></i>', next_text: '<i class="fa fa-angle-right"></i>', @@ -724,7 +724,7 @@ Option | Description | Default }) %> ``` -``` html +```html <!-- Rendered as --> <a href="/1/"><i class="fa fa-angle-left"></i></a> <a href="/1/">1</a> @@ -737,33 +737,33 @@ Option | Description | Default เสียบฟอร์ม search ของ Google เข้า: -``` js +```js <%- search_form(options) %> ``` -Option | Description | Default ---- | --- | --- -`class` | The class name of form | search-form -`text` | Search hint word | Search -`button` | Display search button. The value can be a boolean or a string. When the value is a string, it'll be the text of the button. | false +| Option | Description | Default | +| -------- | --------------------------------------------------------------------------------------------------------------------------- | ----------- | +| `class` | The class name of form | search-form | +| `text` | Search hint word | Search | +| `button` | Display search button. The value can be a boolean or a string. When the value is a string, it'll be the text of the button. | false | ### number_format จัดรูปแบบตัวเลข: -``` js +```js <%- number_format(number, [options]) %> ``` -Option | Description | Default ---- | --- | --- -`precision` | The precision of number. The value can be `false` or a nonnegative integer. | false -`delimiter` | The thousands delimiter | , -`separator` | The separator between the fractional and integer digits. | . +| Option | Description | Default | +| ----------- | --------------------------------------------------------------------------- | ------- | +| `precision` | The precision of number. The value can be `false` or a nonnegative integer. | false | +| `delimiter` | The thousands delimiter | , | +| `separator` | The separator between the fractional and integer digits. | . | **ยกตัวอย่างเช่น:** -``` js +```js <%- number_format(12345.67, {precision: 1}) %> // 12,345.68 @@ -784,13 +784,13 @@ Option | Description | Default Inserts [generator tag](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta). -``` js +```js <%- meta_generator() %> ``` **Examples:** -``` js +```js <%- meta_generator() %> // <meta name="generator" content="Hexo 4.0.0"> ``` @@ -799,47 +799,47 @@ Inserts [generator tag](https://developer.mozilla.org/en-US/docs/Web/HTML/Elemen เสียบข้อมูล [Open Graph] เข้า: -``` js +```js <%- open_graph([options]) %> ``` -Option | Description | Default ---- | --- | --- -`title` | Page title (`og:title`) | `page.title` -`type` | Page type (`og:type`) | article(post page)<br>website(non-post page) -`url` | Page URL (`og:url`) | `url` -`image` | Page images (`og:image`) | All images in the content -`author` | Article author (`og:article:author`) | `config.author` -`date` | Article published time (`og:article:published_time`) | Page published time -`updated` | Article modified time (`og:article:modified_time`) | Page modified time -`language` | Article language (`og:locale`) | `page.lang \|\| page.language \|\| config.language` -`site_name` | Site name (`og:site_name`) | `config.title` -`description` | Page description (`og:description`) | Page excerpt or first 200 characters of the content -`twitter_card` | Twitter card type (`twitter:card`) | summary -`twitter_id` | Twitter ID (`twitter:creator`) | -`twitter_site` | Twitter Site (`twitter:site`) | -`google_plus` | Google+ profile link | -`fb_admins` | Facebook admin ID | -`fb_app_id` | Facebook App ID | +| Option | Description | Default | +| -------------- | ---------------------------------------------------- | --------------------------------------------------- | +| `title` | Page title (`og:title`) | `page.title` | +| `type` | Page type (`og:type`) | article(post page)<br>website(non-post page) | +| `url` | Page URL (`og:url`) | `url` | +| `image` | Page images (`og:image`) | All images in the content | +| `author` | Article author (`og:article:author`) | `config.author` | +| `date` | Article published time (`og:article:published_time`) | Page published time | +| `updated` | Article modified time (`og:article:modified_time`) | Page modified time | +| `language` | Article language (`og:locale`) | `page.lang \|\| page.language \|\| config.language` | +| `site_name` | Site name (`og:site_name`) | `config.title` | +| `description` | Page description (`og:description`) | Page excerpt or first 200 characters of the content | +| `twitter_card` | Twitter card type (`twitter:card`) | summary | +| `twitter_id` | Twitter ID (`twitter:creator`) | +| `twitter_site` | Twitter Site (`twitter:site`) | +| `google_plus` | Google+ profile link | +| `fb_admins` | Facebook admin ID | +| `fb_app_id` | Facebook App ID | ### toc parse แท็ก heading (h1~h6) ในโพสต์และเสียบสารบัญเข้า: -``` js +```js <%- toc(str, [options]) %> ``` -Option | Description | Default ---- | --- | --- -`class` | Class name | toc -`list_number` | Displays list number | true -`max_depth` | Maximum heading depth of generated toc | 6 -`min_depth` | Minimum heading depth of generated toc | 1 +| Option | Description | Default | +| ------------- | -------------------------------------- | ------- | +| `class` | Class name | toc | +| `list_number` | Displays list number | true | +| `max_depth` | Maximum heading depth of generated toc | 6 | +| `min_depth` | Minimum heading depth of generated toc | 1 | **ยกตัวอย่างเช่น:** -``` js +```js <%- toc(page.content) %> ``` @@ -855,7 +855,7 @@ Please see below PRs. - https://github.com/hexojs/hexo/pull/4871 - https://github.com/hexojs/hexo-util/pull/269 - https://github.com/hexojs/hexo-renderer-markdown-it/pull/174 -{% endnote %} + {% endnote %} [color keywords]: http://www.w3.org/TR/css3-color/#svg-color [Moment.js]: http://momentjs.com/ diff --git a/source/th/docs/index.md b/source/th/docs/index.md index 913ef0714d..4a85435ef0 100644 --- a/source/th/docs/index.md +++ b/source/th/docs/index.md @@ -1,8 +1,9 @@ --- title: Documentation --- + ยินดีต้อนรับเข้าสู่ documentation ของ hexo ถ้าคุณพบเจอปัญหาใดๆเวลาใช้ hexo -ไปดูข้อมูลได้ท่ี [troubleshooting guide](troubleshooting.html) ไปเสนอ issue +ไปดูข้อมูลได้ท่ี [troubleshooting guide](troubleshooting.html) ไปเสนอ issue ได้ที่ [GitHub](https://github.com/hexojs/hexo/issues) หรือไปเปิด topic ได้ท่ี [Google Group](https://groups.google.com/group/hexo) ## What is Hexo? @@ -14,7 +15,7 @@ hexo เป็นกรอบบล็อกท่ีรวดเร็ว เ ## Installation -การติดตั้ง hexo ต้องการเวลาหลายนาทีเท่านั้น ถ้าคุณพบเจอปัญหาท่ีแก้ไขไม่ได้ +การติดตั้ง hexo ต้องการเวลาหลายนาทีเท่านั้น ถ้าคุณพบเจอปัญหาท่ีแก้ไขไม่ได้ กรุณาไปเสนอ issue ได้ท่ี [submit a GitHub issue](https://github.com/hexojs/hexo/issues) {% youtube ARted4RniaU %} @@ -28,23 +29,23 @@ hexo เป็นกรอบบล็อกท่ีรวดเร็ว เ ถ้าคุณติดตั้งสองสิ่งนี้อยู่แล้วในคอม ขอแสดงความยินดี คุณจะติดตั้ง hexo ด้วย npm ได้อย่างนี้: -``` bash +```bash $ npm install -g hexo-cli ``` ถ้าคุณยังไม่ได้ติดตั้งสองสิ่งนี้ กรุณาปฏิบัติตามวิธีการใช้เพื่อติดตั้งทุกสิ่งท่ีต้องการ {% note warn For Mac users %} -คุณอาจจะพบปัญหาบ้างเมื่อ compiling กรุณาติดตั้ง Xcode จาก App Store ก่อน +คุณอาจจะพบปัญหาบ้างเมื่อ compiling กรุณาติดตั้ง Xcode จาก App Store ก่อน เสร็จแล้วค่อยไปเปิด Xcode และ ไปถึง **Preferences -> Download -> Command Line - Tools -> Install** เพื่อติดตั้งเครื่องมือคำสั่ง +Tools -> Install** เพื่อติดตั้งเครื่องมือคำสั่ง {% endnote %} ### Install Git - Windows: ดาวน์โหลด & ติดตั้ง [git](https://git-scm.com/download/win). - Mac: ติดตั้งด้วย [Homebrew](http://mxcl.github.com/homebrew/), [MacPorts] -(http://www.macports.org/) หรือ [installer](http://sourceforge -.net/projects/git-osx-installer/). + (http://www.macports.org/) หรือ [installer](http://sourceforge + .net/projects/git-osx-installer/). - Linux (Ubuntu, Debian): `sudo apt-get install git-core` - Linux (Fedora, Red Hat, CentOS): `sudo yum install git-core` @@ -77,7 +78,7 @@ If you installed Node.js using Snap, you may need to manually run `npm install` เมื่อความต้องการทุกอย่างได้ติดตั้งเรียบร้อยแล้ว คุณสามารถติดตั้ง hexo ด้วย npm -``` bash +```bash $ npm install -g hexo-cli ``` @@ -89,15 +90,15 @@ Please note we do not provide bugfixes to past versions of Hexo. We highly recommend to always install the [latest version](https://www.npmjs.com/package/hexo?activeTab=versions) of Hexo and the [recommended version](#Requirements) of Node.js, whenever possible. -Hexo version | Minimum (Node.js version) | Less than (Node.js version) ---- | --- | --- -7.0+ | 14.0.0 | latest -6.2+ | 12.13.0 | latest -6.0+ | 12.13.0 | 18.5.0 -5.0+ | 10.13.0 | 12.0.0 -4.1 - 4.2 | 8.10 | 10.0.0 -4.0 | 8.6 | 8.10.0 -3.3 - 3.9 | 6.9 | 8.0.0 -3.2 - 3.3 | 0.12 | unknown -3.0 - 3.1 | 0.10 or iojs | unknown -0.0.1 - 2.8 | 0.10 | unknown \ No newline at end of file +| Hexo version | Minimum (Node.js version) | Less than (Node.js version) | +| ------------ | ------------------------- | --------------------------- | +| 7.0+ | 14.0.0 | latest | +| 6.2+ | 12.13.0 | latest | +| 6.0+ | 12.13.0 | 18.5.0 | +| 5.0+ | 10.13.0 | 12.0.0 | +| 4.1 - 4.2 | 8.10 | 10.0.0 | +| 4.0 | 8.6 | 8.10.0 | +| 3.3 - 3.9 | 6.9 | 8.0.0 | +| 3.2 - 3.3 | 0.12 | unknown | +| 3.0 - 3.1 | 0.10 or iojs | unknown | +| 0.0.1 - 2.8 | 0.10 | unknown | diff --git a/source/th/docs/internationalization.md b/source/th/docs/internationalization.md index 373ecb7bcb..6711ab1c96 100644 --- a/source/th/docs/internationalization.md +++ b/source/th/docs/internationalization.md @@ -1,11 +1,12 @@ --- title: Internationalization (i18n) --- -คุณสามารถใช้ internationalization มาโชว์ไซต์ของคุณด้วยภาษาต่างๆ ภาษา dafault -ของไซต์นั้นแก้ไขได้ใน `language` ของ `_config.yml` + +คุณสามารถใช้ internationalization มาโชว์ไซต์ของคุณด้วยภาษาต่างๆ ภาษา dafault +ของไซต์นั้นแก้ไขได้ใน `language` ของ `_config.yml` คุณยังตั้งค่าหลายภาษาและแก้ไขลำดับของภาษา default ได้เช่นกัน -``` yaml +```yaml language: zh-tw language: @@ -15,15 +16,15 @@ language: ### Language Files -ไฟล์ของภาษาจะเป็นไฟล์ YAML หรือ JSON คุณต้องไลฟ์เหล่านี้อยู่ใน folder +ไฟล์ของภาษาจะเป็นไฟล์ YAML หรือ JSON คุณต้องไลฟ์เหล่านี้อยู่ใน folder `language` ของธีม สำหรับข้อมูลเพิ่มเติมของไฟล์ภาษา ไปดูได้ท่ี [printf format](https://github.com/alexei/sprintf.js) ### Templates -คุณใช้ helper ของ `__` หรือ `_p` ใน template ได้เพื่อได้ string ท่ีแปลมาแล้ว - ตัวแรกใช้ในกรณีทางการ ส่วนตัวหลังใช้ในกรณีท่ีมีหลาย string ยกตัวอย่างเช่น: +คุณใช้ helper ของ `__` หรือ `_p` ใน template ได้เพื่อได้ string ท่ีแปลมาแล้ว +ตัวแรกใช้ในกรณีทางการ ส่วนตัวหลังใช้ในกรณีท่ีมีหลาย string ยกตัวอย่างเช่น: -``` yaml en.yml +```yaml en.yml index: title: Home add: Add @@ -33,7 +34,7 @@ index: other: %d videos ``` -``` js +```js <%= __('index.title') %> // Home @@ -43,21 +44,21 @@ index: ### Path -คุณสามารถตั้งค่าภาษาของเพจได้ใน front-matter หรือแก้ไขการตั้งค่า `i18n_dir` +คุณสามารถตั้งค่าภาษาของเพจได้ใน front-matter หรือแก้ไขการตั้งค่า `i18n_dir` ได้ใน `_config.yml` เพื่อ enable การเฝ้าดูไฟล์ของ hexo -``` yaml +```yaml i18n_dir: :lang ``` -default value ของการตั้งค่า `i18n_dir` คือ `:lang` ซึ่งหมายความว่า hexo +default value ของการตั้งค่า `i18n_dir` คือ `:lang` ซึ่งหมายความว่า hexo จะสืบค้นภาษาท่ีอยู่ใน segment ตัวแรกของ URL ยกตัวอย่างเช่น: -``` plain +```plain /index.html => en /archives/index.html => en /zh-tw/index.html => zh-tw ``` string นั้นจะมีผลได้ในแต่กรณีท่ีไลฟ์ภาษานั้นมีอยู่จริงๆ ดังนั้น `archives` ใน - `/archives/index.html` (ตัวอย่างท่ีสอง) จะไม่เกิดผลในการตั้งค่าภาษาของเว็บไซต์ +`/archives/index.html` (ตัวอย่างท่ีสอง) จะไม่เกิดผลในการตั้งค่าภาษาของเว็บไซต์ diff --git a/source/th/docs/migration.md b/source/th/docs/migration.md index 76cd5dde37..7f67957a71 100644 --- a/source/th/docs/migration.md +++ b/source/th/docs/migration.md @@ -1,36 +1,37 @@ --- title: Migration --- + ## RSS ขั้นแรก ติดตั้งปลั๊กอิน `hexo-migrator-rss` -``` bash +```bash $ npm install hexo-migrator-rss --save ``` -เมื่อเสร็จการติดตั้งปลั๊กอินแล้วรันคำสั่งต่อไปเพื่อย้ายโพสต์ทั้งหมดจาก RSS +เมื่อเสร็จการติดตั้งปลั๊กอินแล้วรันคำสั่งต่อไปเพื่อย้ายโพสต์ทั้งหมดจาก RSS `source` นั้นเป็น path ของไฟล์หรือ URL ได้ -``` bash +```bash $ hexo migrate rss <source> ``` ## Jekyll -ย้ายไฟล์ทั้งหมดใน folder Jekyll `_posts` ไป folder `source/_posts` +ย้ายไฟล์ทั้งหมดใน folder Jekyll `_posts` ไป folder `source/_posts` แก้ไขการตั้งค่า `new_post_name` ใน `_config.yml`: -``` yaml +```yaml new_post_name: :year-:month-:day-:title.md ``` ## Octopress -ย้ายไฟล์ทั้งหมดใน folder `source/_posts` ของ Octopress ไปถึง `source/_posts` +ย้ายไฟล์ทั้งหมดใน folder `source/_posts` ของ Octopress ไปถึง `source/_posts` แก้ไขการตั้งค่า `new_post_name` ใน `_config.yml`: -``` yaml +```yaml new_post_name: :year-:month-:day-:title.md ``` @@ -38,20 +39,20 @@ new_post_name: :year-:month-:day-:title.md ขั้นแรก ติดตั้งปลั๊กอิน `hexo-migrator-wordpress` -``` bash +```bash $ npm install hexo-migrator-wordpress --save ``` นำไซตื WordPress ของคุณออกไปได้ด้วยการตั้งค่า "Tools" → "Export" → -"WordPress" ใน dashboard ของ WordPress (สำหรับข้อมูลเพิ่มเติมไปดูที่ [WordPress support page](http://en.support.wordpress.com/export/)) +"WordPress" ใน dashboard ของ WordPress (สำหรับข้อมูลเพิ่มเติมไปดูที่ [WordPress support page](http://en.support.wordpress.com/export/)) แล้วรัน: -``` bash +```bash $ hexo migrate wordpress <source> ``` -`source` เป็น path ของไฟล์หรือ URL ของไฟล์ท่ี WordPress ท่ีส่งออกมา +`source` เป็น path ของไฟล์หรือ URL ของไฟล์ท่ี WordPress ท่ีส่งออกมา ## Joomla @@ -61,7 +62,7 @@ $ hexo migrate wordpress <source> $ npm install hexo-migrator-joomla --save ``` -นำออกบทความ Joomla ของคุณได้โดยใช้ component [J2XML](http://extensions.joomla.org/extensions/migration-a-conversion/data-import-a-export/12816?qh=YToxOntpOjA7czo1OiJqMnhtbCI7fQ%3D%3D) +นำออกบทความ Joomla ของคุณได้โดยใช้ component [J2XML](http://extensions.joomla.org/extensions/migration-a-conversion/data-import-a-export/12816?qh=YToxOntpOjA7czo1OiJqMnhtbCI7fQ%3D%3D) แล้วรัน: @@ -69,4 +70,4 @@ $ npm install hexo-migrator-joomla --save $ hexo migrate joomla <source> ``` -`source` เป็น path ของไฟล์หรือ URL ของไฟล์ท่ี Joomla ท่ีส่งออกมา +`source` เป็น path ของไฟล์หรือ URL ของไฟล์ท่ี Joomla ท่ีส่งออกมา diff --git a/source/th/docs/one-command-deployment.md b/source/th/docs/one-command-deployment.md index 5f5fc11590..c0725f4aaa 100644 --- a/source/th/docs/one-command-deployment.md +++ b/source/th/docs/one-command-deployment.md @@ -1,30 +1,31 @@ --- title: Deployment --- + hexo สนับสนุนวิธีรวดเร็วและเรียบง่ายสำหรับ deployment คุณ deploy เว็บไซต์ของคุณไปถึงเซร์ฟเวอร์ได้ด้วยคำสั่งบรรทัดเดียว -``` bash +```bash $ hexo deploy ``` ก่อน deployment ครั้งแรกของคุณ คุณต้องการแก้ไขการตั้งค่าบางอย่างใน `_config -.yml` การตั้งค่า deployment ท่ีเกิดผลได้ต้องมี field ท่ีเป็น `type` +.yml` การตั้งค่า deployment ท่ีเกิดผลได้ต้องมี field ท่ีเป็น `type` ยกตัวอย่างเช่น: -``` yaml +```yaml deploy: type: git ``` คุณยังเลื่อก deployer ได้หลายตัว hexo จะ execute deployer ทุกตัวตามลำดับ -``` yaml +```yaml deploy: -- type: git - repo: -- type: heroku - repo: + - type: git + repo: + - type: heroku + repo: ``` Refer to the [Plugins](https://hexo.io/plugins/) list for more deployment plugins. @@ -47,17 +48,17 @@ deploy: message: [message] ``` -Option | Description | Default ---- | --- | --- -`repo` | URL of the target repository | -`branch` | Branch name. | `gh-pages` (GitHub)<br>`coding-pages` (Coding.net)<br>`master` (others) -`message` | Customize commit message. | `Site updated: {% raw %}{{ now('YYYY-MM-DD HH:mm:ss') }}{% endraw %}` -`token` | Optional token value to authenticate with the repo. Prefix with `$` to read token from environment variable +| Option | Description | Default | +| --------- | ----------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- | +| `repo` | URL of the target repository | +| `branch` | Branch name. | `gh-pages` (GitHub)<br>`coding-pages` (Coding.net)<br>`master` (others) | +| `message` | Customize commit message. | `Site updated: {% raw %}{{ now('YYYY-MM-DD HH:mm:ss') }}{% endraw %}` | +| `token` | Optional token value to authenticate with the repo. Prefix with `$` to read token from environment variable | 3. Deploy your site `hexo clean && hexo deploy`. - - You will be prompted with username and password of the target repository, unless you authenticate with a token or ssh key. - - hexo-deployer-git does not store your username and password. Use [git-credential-cache](https://git-scm.com/docs/git-credential-cache) to store them temporarily. +- You will be prompted with username and password of the target repository, unless you authenticate with a token or ssh key. +- hexo-deployer-git does not store your username and password. Use [git-credential-cache](https://git-scm.com/docs/git-credential-cache) to store them temporarily. 4. Navigate to your repository settings and change the "Pages" branch to `gh-pages` (or the branch specified in your config). The deployed site should be live on the link shown on the "Pages" setting. @@ -65,23 +66,23 @@ Option | Description | Default ติดตั้ง [hexo-deployer-heroku]. -``` bash +```bash $ npm install hexo-deployer-heroku --save ``` แก้ไขการตั้งค่า -``` yaml +```yaml deploy: type: heroku repo: <repository url> message: [message] ``` -Option | Description ---- | --- -`repo`, `repository` | Heroku repository URL -`message` | Customize commit message (Default to `Site updated: {% raw %}{{ now('YYYY-MM-DD HH:mm:ss') }}{% endraw %}`) +| Option | Description | +| -------------------- | ----------------------------------------------------------------------------------------------------------- | +| `repo`, `repository` | Heroku repository URL | +| `message` | Customize commit message (Default to `Site updated: {% raw %}{{ now('YYYY-MM-DD HH:mm:ss') }}{% endraw %}`) | ## Netlify @@ -92,8 +93,8 @@ Option | Description เป็นแพลตฟอร์มซึ่งรวมทุกอย่างเป็นหนึ่งเดียว ทำให้การสร้างไซต์หรือแอปของแว็บท่ีมีแระสิทธิภาพและรักษาได้ง่ายนั้นเป็นขบวนการอัตโนมัติ - มีทั้งหมดสองวิธีในเรื่อง deploy เว็บไซต์ของตน วิธีทั่วไปท่ีสุดคือการใช้ web - UI คุณสามารถไปท่ี [create a new site page](https://app.netlify.com/start) และเลือก repo ของ project คุณจาก Github Gitlab หรือ Bitbucket และทำตามวิธีการใช้ +มีทั้งหมดสองวิธีในเรื่อง deploy เว็บไซต์ของตน วิธีทั่วไปท่ีสุดคือการใช้ web +UI คุณสามารถไปท่ี [create a new site page](https://app.netlify.com/start) และเลือก repo ของ project คุณจาก Github Gitlab หรือ Bitbucket และทำตามวิธีการใช้ วิธีท่ีสองคือ การใช้เครื่องมือ [Node based CLI](https://www.netlify.com/docs/cli/) ของ Netlify เพื่อบริหารและ deploy ไซต์บน Netlify โดยไม่ต้องผ่าน terminal @@ -105,13 +106,13 @@ copy respository ของคุณและ deploy ไปถึง Netlify ด ติดตั้ง [hexo-deployer-rsync]. -``` bash +```bash $ npm install hexo-deployer-rsync --save ``` แก้ไขการตั้งค่า -``` yaml +```yaml deploy: type: rsync host: <host> @@ -123,49 +124,49 @@ deploy: ignore_errors: [true|false] ``` -Option | Description | Default ---- | --- | --- -`host` | Address of remote host | -`user` | Username | -`root` | Root directory of remote host | -`port` | Port | 22 -`delete` | Delete old files on remote host | true -`verbose` | Display verbose messages | true -`ignore_errors` | Ignore errors | false +| Option | Description | Default | +| --------------- | ------------------------------- | ------- | +| `host` | Address of remote host | +| `user` | Username | +| `root` | Root directory of remote host | +| `port` | Port | 22 | +| `delete` | Delete old files on remote host | true | +| `verbose` | Display verbose messages | true | +| `ignore_errors` | Ignore errors | false | ## OpenShift ติดตั้ง [hexo-deployer-openshift]. -``` bash +```bash $ npm install hexo-deployer-openshift --save ``` แก้ไขการตั้งค่า -``` yaml +```yaml deploy: type: openshift repo: <repository url> message: [message] ``` -Option | Description ---- | --- -`repo` | OpenShift repository URL -`message` | Customize commit message (Default to `Site updated: {% raw %}{{ now('YYYY-MM-DD HH:mm:ss') }}{% endraw %}`) +| Option | Description | +| --------- | ----------------------------------------------------------------------------------------------------------- | +| `repo` | OpenShift repository URL | +| `message` | Customize commit message (Default to `Site updated: {% raw %}{{ now('YYYY-MM-DD HH:mm:ss') }}{% endraw %}`) | ## FTPSync ติดตั้ง [hexo-deployer-ftpsync]. -``` bash +```bash $ npm install hexo-deployer-ftpsync --save ``` แก้ไขการตั้งค่า -``` yaml +```yaml deploy: type: ftpsync host: <host> @@ -177,27 +178,29 @@ deploy: verbose: [true|false] ``` -Option | Description | Default ---- | --- | --- -`host` | Address of remote host | -`user` | Username | -`pass` | Password | -`remote` | Root directory of remote host | `/` -`port` | Port | 21 -`clear` | Remove all files and directories from the remote directory before upload | 1 -`verbose` | Display verbose messages | false +| Option | Description | Default | +| ------------- | ------------------------------------------------------------------------ | ------- | +| `host` | Address of remote host | +| `user` | Username | +| `pass` | Password | +| `remote` | Root directory of remote host | `/` | +| `port` | Port | 21 | +| `clear` | Remove all files and directories from the remote directory before upload | 1 | +| `ignore` | Ignore the files on either host or remote | +| `connections` | Connections number | 1 | +| `verbose` | Display verbose messages | false | ## SFTP ติดตั้ง [hexo-deployer-sftp]. deploy ไซต์ได้โดย SFTP และใช้ password ได้ด้วย ssh-agent -``` bash +```bash $ npm install hexo-deployer-sftp --save ``` แก้ไขการตั้งค่า -``` yaml +```yaml deploy: type: sftp host: <host> @@ -210,16 +213,16 @@ deploy: agent: [path/to/agent/socket] ``` -Option | Description | Default ---- | --- | --- -`host` | Address of remote host | -`user` | Username | -`pass` | Password | -`remotePath` | Root directory of remote host | `/` -`port` | Port | 22 -`privateKey` | Path to a ssh private key | -`passphrase` | Optional passphrase for the private key | -`agent` | Path to the ssh-agent socket | `$SSH_AUTH_SOCK` +| Option | Description | Default | +| ------------ | --------------------------------------- | ---------------- | +| `host` | Address of remote host | +| `user` | Username | +| `pass` | Password | +| `remotePath` | Root directory of remote host | `/` | +| `port` | Port | 22 | +| `privateKey` | Path to a ssh private key | +| `passphrase` | Optional passphrase for the private key | +| `agent` | Path to the ssh-agent socket | `$SSH_AUTH_SOCK` | ## Vercel @@ -277,8 +280,8 @@ After a few moments, your website will be deployed. 2. แก้ไขการกำหนดค่า - ``` yaml - deploy: +```yaml +deploy: - type: rss3 endpoint: https://hub.rss3.io privateKey: 47e18d6c386898b424025cd9db446f779ef24ad33a26c499c87bb3d9372540ba @@ -288,15 +291,15 @@ After a few moments, your website will be deployed. api: key: d693df715d3631e489d6 secret: ee8b74626f12b61c1a4bde3b8c331ad390567c86ba779c9b18561ee92c1cbff0 - ``` - -| พารามิเตอร์ | คำอธิบาย | -| ----------------- | ---------------------- | -| `deploy` | ลิงก์ไปยัง RSS3 Hub | -| `privateKey` | คีย์ส่วนตัวของคุณ 64 ไบต์ | -| `ipfs/deploy` | ว่าจะปรับใช้กับ IPFS หรือไม่ | -| `ipfs/gateway` | IPFS API เกตเวย์ | -| `ipfs/api/key` | เนื้อหาการตรวจสอบที่เกี่ยวข้องกับเกตเวย์ IPFS | +``` + +| พารามิเตอร์ | คำอธิบาย | +| ----------------- | --------------------------------------------- | +| `deploy` | ลิงก์ไปยัง RSS3 Hub | +| `privateKey` | คีย์ส่วนตัวของคุณ 64 ไบต์ | +| `ipfs/deploy` | ว่าจะปรับใช้กับ IPFS หรือไม่ | +| `ipfs/gateway` | IPFS API เกตเวย์ | +| `ipfs/api/key` | เนื้อหาการตรวจสอบที่เกี่ยวข้องกับเกตเวย์ IPFS | | `ipfs/api/secret` | การตรวจสอบเนื้อหาที่เกี่ยวข้องกับเกตเวย์ IPFS | 3. สร้างไฟล์แบบคงที่ diff --git a/source/th/docs/permalinks.md b/source/th/docs/permalinks.md index 45fd23c46d..cb1ef277c0 100644 --- a/source/th/docs/permalinks.md +++ b/source/th/docs/permalinks.md @@ -1,6 +1,7 @@ --- title: Permalinks --- + คุณสามารถตั้งค่า permalink ของเว็บไซตืตนในไฟล์ `_config.yml` หรือใน front-matter ของทุกโพสต์ @@ -8,80 +9,80 @@ front-matter ของทุกโพสต์ Besides the following variables, you can use any attributes in the permalink except `:path` and `:permalink`. -Variable | Description ---- | --- -`:year` | Published year of posts (4-digit) -`:month` | Published month of posts (2-digit) -`:i_month` | Published month of posts (Without leading zeros) -`:day` | Published day of posts (2-digit) -`:i_day` | Published day of posts (Without leading zeros) -`:hour` | Published hour of posts (2-digit) -`:minute` | Published minute of posts (2-digit) -`:second` | Published second of posts (2-digit) -`:title` | Filename (relative to "source/_posts/" folder) -`:name` | Filename -`:post_title` | Post title -`:id` | Post ID (_not persistent across [cache reset](/th/docs/commands#clean)_) -`:category` | Categories. If the post is uncategorized, it will use the `default_category` value. -`:hash` | SHA1 hash of filename (same as `:title`) and date (12-hexadecimal) +| Variable | Description | +| ------------- | ----------------------------------------------------------------------------------- | +| `:year` | Published year of posts (4-digit) | +| `:month` | Published month of posts (2-digit) | +| `:i_month` | Published month of posts (Without leading zeros) | +| `:day` | Published day of posts (2-digit) | +| `:i_day` | Published day of posts (Without leading zeros) | +| `:hour` | Published hour of posts (2-digit) | +| `:minute` | Published minute of posts (2-digit) | +| `:second` | Published second of posts (2-digit) | +| `:title` | Filename (relative to "source/\_posts/" folder) | +| `:name` | Filename | +| `:post_title` | Post title | +| `:id` | Post ID (_not persistent across [cache reset](/th/docs/commands#clean)_) | +| `:category` | Categories. If the post is uncategorized, it will use the `default_category` value. | +| `:hash` | SHA1 hash of filename (same as `:title`) and date (12-hexadecimal) | ตุณสามารถตั้งค่า default value ของทุก variable ใน permalink โดยตั้งค่า `permalink_defaults`: -``` yaml +```yaml permalink_defaults: lang: en ``` ### Examples -``` yaml source/_posts/hello-world.md +```yaml source/_posts/hello-world.md title: Hello World date: 2013-07-14 17:01:34 categories: -- foo -- bar + - foo + - bar ``` -Setting | Result ---- | --- -`:year/:month/:day/:title/` | 2013/07/14/hello-world/ -`:year-:month-:day-:title.html` | 2013-07-14-hello-world.html -`:category/:title/` | foo/bar/hello-world/ -`:title-:hash/` | hello-world-a2c8ac003b43/ +| Setting | Result | +| ------------------------------- | --------------------------- | +| `:year/:month/:day/:title/` | 2013/07/14/hello-world/ | +| `:year-:month-:day-:title.html` | 2013-07-14-hello-world.html | +| `:category/:title/` | foo/bar/hello-world/ | +| `:title-:hash/` | hello-world-a2c8ac003b43/ | -``` yaml source/_posts/lorem/hello-world.md +```yaml source/_posts/lorem/hello-world.md title: Hello World date: 2013-07-14 17:01:34 categories: -- foo -- bar + - foo + - bar ``` -Setting | Result ---- | --- -`:year/:month/:day/:title/` | 2013/07/14/lorem/hello-world/ -`:year/:month/:day/:name/` | 2013/07/14/hello-world/ +| Setting | Result | +| --------------------------- | ----------------------------- | +| `:year/:month/:day/:title/` | 2013/07/14/lorem/hello-world/ | +| `:year/:month/:day/:name/` | 2013/07/14/hello-world/ | ### Multi-language Support เมื่อสร้างเว็บไซต์ท่ีสนับสนุนหลายภาษา คุณสามารถแก้ไขการตั้งค่า -`new_post_name` และ `permalink` อย่างนี้: +`new_post_name` และ `permalink` อย่างนี้: -``` yaml +```yaml new_post_name: :lang/:title.md permalink: :lang/:title/ ``` เมื่อคุณสร้างโพสต์ใหม่ออกมา โพสต์นั้นจะถูกบันทึกไปถึง: -``` bash +```bash $ hexo new "Hello World" --lang tw # => source/_posts/tw/Hello-World.md ``` และ URL จะเป็นอย่างนี้: -``` plain +```plain http://localhost:4000/tw/hello-world/ ``` diff --git a/source/th/docs/plugins.md b/source/th/docs/plugins.md index 2b8f7bc2a5..132fd4c3e8 100644 --- a/source/th/docs/plugins.md +++ b/source/th/docs/plugins.md @@ -1,13 +1,14 @@ --- title: Plugins --- + hexo มีระบบปลั๊กอินท่ีมีประสิทธิภาพ ซึ่งทำให้มันง่ายท่ีจะขยาย function ต่างๆโดยไม่ต้องแก้ไข source code ของ module สำคัญ ใน hexo มีปลั๊กอินสองอย่างทั้งหมด: ### Script ถ้าปลั๊กอินของคุณไม่ซับซ้อนเท่าไร การท่ีคุณต้องทำคือวางไฟล์ JavaScript -ของคุณอยู่ใน folder `script` เท่านั้น hexo จะโหลดไฟล์นั้นในช่วง initialization +ของคุณอยู่ใน folder `script` เท่านั้น hexo จะโหลดไฟล์นั้นในช่วง initialization ### Plugin @@ -19,7 +20,7 @@ folder ใหม่ของคุณต้องการมีไฟล์อ JavaScript code ของตน และอีกอย่างหนึ่งเป็นไฟล์ `package.json` ท่ีเขียนเจตนาการสร้างปลั๊กอินนี้และ dependency ของมัน -``` plain +```plain . ├── index.js └── package.json @@ -28,7 +29,7 @@ JavaScript code ของตน และอีกอย่างหนึ่ง ในช่วงแรกๆ คุณต้องตั้งค่า entry ของ `name` `version` และ `main` ในไฟล์ `package.json` ยกตัวอย่างเชน: -``` json package.json +```json package.json { "name": "hexo-my-plugin", "version": "0.0.1", @@ -36,7 +37,7 @@ JavaScript code ของตน และอีกอย่างหนึ่ง } ``` -คุณยังต้องเขียนชื่อปลั๊กอินของตนเป็น dependency ในไฟล์ `package.json` ท่ีเป็น root ของ hexo ดังนั้น hexo จะได้สืบค้นและโหลดปลั๊กอินนี้ +คุณยังต้องเขียนชื่อปลั๊กอินของตนเป็น dependency ในไฟล์ `package.json` ท่ีเป็น root ของ hexo ดังนั้น hexo จะได้สืบค้นและโหลดปลั๊กอินนี้ ### Tools @@ -56,23 +57,21 @@ JavaScript code ของตน และอีกอย่างหนึ่ง 1. Fork [hexojs/site] 2. Clone the repository to your computer and install dependencies. - {% code %} - $ git clone https://github.com/<username>/site.git - $ cd site - $ npm install - {% endcode %} + {% code %} + $ git clone https://github.com/<username>/site.git + $ cd site + $ npm install + {% endcode %} 3. Edit `source/_data/plugins.yml` and add your plugin. For example: - {% code %} - - name: hexo-server - description: Server module for Hexo. - link: <https://github.com/hexojs/hexo-server> - tags: - - official - - server - - console - {% endcode %} + {% code %} + + - name: hexo-server + description: Server module for Hexo. + link: <https://github.com/hexojs/hexo-server> + tags: - official - server - console + {% endcode %} 4. Push the branch. 5. Create a pull request and describe the change. diff --git a/source/th/docs/server.md b/source/th/docs/server.md index 983325bd22..087800d16a 100644 --- a/source/th/docs/server.md +++ b/source/th/docs/server.md @@ -1,11 +1,12 @@ --- title: Server --- + ## [hexo-server] -ด้วยการประกาศของ hexo 3 เซิร์ฟเวอร์ถูกย้ายออกมากจาก module หลัก คุณต้องการติดตั้ง [hexo-server] ก่อนการเริ่มใช้เซิร์ฟเวอร์ +ด้วยการประกาศของ hexo 3 เซิร์ฟเวอร์ถูกย้ายออกมากจาก module หลัก คุณต้องการติดตั้ง [hexo-server] ก่อนการเริ่มใช้เซิร์ฟเวอร์ -``` bash +```bash $ npm install hexo-server --save ``` @@ -13,24 +14,24 @@ $ npm install hexo-server --save เว็บไซต์ของคุณจะรันอยู่ท่ี `http://localhost:4000` by default เมื่อเซิร์ฟเวอร์รันอยู่ hexo จะเฝ้าดูการเปลี่ยนแปลงของไฟล์และอัปเดทโดยอัตโนมัติ ดังนั้นจะไม่ต้องเปิดใหม่ด้วยตน -``` bash +```bash $ hexo server ``` If you want to change the port or if you're encountering `EADDRINUSE` errors, use the `-p` option to set a different port. ถ้าคุณอยากเปลี่ยน port หรือพบข้อผิดพลาดว่า `EADDRINUSE` ใช้ตัวเลือก `-p` ไปตั้งค่าเป็น port อื่น -``` bash +```bash $ hexo server -p 5000 ``` ### Static Mode -ในโหมดคงที่ ระบบจะเฝ้าดูแต่ไฟล์ท่ีอยู่ใน folder `public` -เท่านั้นและไม่เฝ้าดูไฟล์อื่นๆ คุณต้องรันคำสั่ง `hexo generate` +ในโหมดคงที่ ระบบจะเฝ้าดูแต่ไฟล์ท่ีอยู่ใน folder `public` +เท่านั้นและไม่เฝ้าดูไฟล์อื่นๆ คุณต้องรันคำสั่ง `hexo generate` ก่อนเปิดเซิร์ฟเวอร์ โหลดนี้ปกติใช้แต่ในกรณี production -``` bash +```bash $ hexo server -s ``` @@ -38,7 +39,7 @@ $ hexo server -s hexo รันเซิร์ฟเวอร์อยู่ท่ี `0.0.0.0` by default คุณสามารถเปลียนการตั้งค่า IP default นี้ -``` bash +```bash $ hexo server -i 192.168.1.1 ``` @@ -48,7 +49,7 @@ $ hexo server -i 192.168.1.1 ### Install -``` bash +```bash $ curl get.pow.cx | sh ``` @@ -56,12 +57,12 @@ $ curl get.pow.cx | sh symlink folder เข้า `~/.pow` -``` bash +```bash $ cd ~/.pow $ ln -s /path/to/myapp ``` -เว็บไซต์ของคุณจะรันอยุ่ท่ี `http://myapp.test` URL นั้นจะอยู่บน symlink +เว็บไซต์ของคุณจะรันอยุ่ท่ี `http://myapp.test` URL นั้นจะอยู่บน symlink ท่ีตั้งขึ้นมา [hexo-server]: https://github.com/hexojs/hexo-server diff --git a/source/th/docs/setup.md b/source/th/docs/setup.md index c9b24c1716..86851395cb 100644 --- a/source/th/docs/setup.md +++ b/source/th/docs/setup.md @@ -6,7 +6,7 @@ title: Setup เมื่อติดตั้ง hexo แล้ว รันคำสั่งต่อไปเพื่อ initialize hexo ใน `<folder>` -``` bash +```bash $ hexo init <folder> $ cd <folder> $ npm install @@ -14,7 +14,7 @@ $ npm install เมื่อเสร็จการ initialization โครงสร้าง folder ของ project คุณจะเป็นอย่างนี้: -``` plain +```plain . ├── _config.yml ├── package.json @@ -25,17 +25,17 @@ $ npm install └── themes ``` -### _config.yml +### \_config.yml -ไฟล์ของไซต์ [configuration](configuration.html) คุณสามารถตั้งค่ามากขึ้น ณ +ไฟล์ของไซต์ [configuration](configuration.html) คุณสามารถตั้งค่ามากขึ้น ณ ท่ีนี้ ### package.json -ข้อมูลของแอป. renderer ของ [EJS](https://ejs.co/) [Stylus](http://learnboost.github.io/stylus/) และ [Markdown](http://daringfireball.net/projects/markdown/) +ข้อมูลของแอป. renderer ของ [EJS](https://ejs.co/) [Stylus](http://learnboost.github.io/stylus/) และ [Markdown](http://daringfireball.net/projects/markdown/) จะติดตั้ง by default คุณสามารถลยออก renderer พวกนี้ได้ในเวลาภายหลัง -``` json package.json +```json package.json { "name": "hexo-site", "version": "0.0.0", @@ -59,16 +59,16 @@ $ npm install ### scaffolds -folder [Scaffold](writing.html#Scaffolds) เมื่อคุณสร้างโพสต์ใหม่ขึ้นมา hexo +folder [Scaffold](writing.html#Scaffolds) เมื่อคุณสร้างโพสต์ใหม่ขึ้นมา hexo จะเรียงข้อมูลไฟล์ตาม folder นี้ ### source -source folder. ท่ีนี้เป็นท่ีวางเนื้อหาเว็บไซต์ของคุณ hexo -ละเลยไฟล์ท่ีถูกซ่อนหรือ folder ท่ีมี `_` เป็นคำนำหน้าในชื่อไฟล์ (นอกจาก -folder `_posts`) ไฟล์ท่ี renderable (เช่น Markdown และ HTML) +source folder. ท่ีนี้เป็นท่ีวางเนื้อหาเว็บไซต์ของคุณ hexo +ละเลยไฟล์ท่ีถูกซ่อนหรือ folder ท่ีมี `_` เป็นคำนำหน้าในชื่อไฟล์ (นอกจาก +folder `_posts`) ไฟล์ท่ี renderable (เช่น Markdown และ HTML) จะถูกจถูกจัดการและใส่เข้า folder `public` ในเมื่อไฟล์อื่นๆจะถูก copy เท่านั้น ### themes -folder [Theme](themes.html) hexo generate เว็บไซต์คงที่ด้วยผสมเนื่อหาของไซต์กับธีม +folder [Theme](themes.html) hexo generate เว็บไซต์คงที่ด้วยผสมเนื่อหาของไซต์กับธีม diff --git a/source/th/docs/syntax-highlight.md b/source/th/docs/syntax-highlight.md index 3f2765eed5..cc1327965e 100644 --- a/source/th/docs/syntax-highlight.md +++ b/source/th/docs/syntax-highlight.md @@ -17,7 +17,7 @@ code snippet code snippet {% endcode %} -``` [language] [title] [url] [link text] [additional options] +```[language] [title] [url] [link text] [additional options] code snippet ``` ```` @@ -35,7 +35,7 @@ highlight: auto_detect: false line_number: true line_threshold: 0 - tab_replace: '' + tab_replace: "" exclude_languages: - example wrap: true @@ -45,7 +45,7 @@ prismjs: preprocess: true line_number: true line_threshold: 0 - tab_replace: '' + tab_replace: "" ``` The YAML above is Hexo's default configuration. @@ -85,7 +85,7 @@ highlight: auto_detect: false line_number: true line_threshold: 0 - tab_replace: ' ' + tab_replace: " " exclude_languages: - example wrap: true @@ -116,18 +116,18 @@ Hexo adds line number by wrapping output inside `<figure>` and `<table>`: ```html <figure class="highlight yaml"> -<table> -<tbody> -<tr> - <td class="gutter"> - <pre><span class="line">1</span><br></pre> - </td> - <td class="code"> - <pre><span class="line"><span class="attr">hello:</span><span class="string">hexo</span></span><br></pre> - </td> -</tr> -</tbody> -</table> + <table> + <tbody> + <tr> + <td class="gutter"> + <pre><span class="line">1</span><br></pre> + </td> + <td class="code"> + <pre><span class="line"><span class="attr">hello:</span><span class="string">hexo</span></span><br></pre> + </td> + </tr> + </tbody> + </table> </figure> ``` @@ -143,7 +143,6 @@ Accepts an optional threshold to only show line numbers as long as the numbers o Replace tabs inside code block with given string. By default it is 2 spaces. - ### exclude_languages (+6.1.0) Only wrap with `<pre><code class="lang"></code></pre>` and will not render all tags(`span`, and `br`) in content if are languages matches this option. @@ -187,7 +186,7 @@ prismjs: preprocess: true line_number: true line_threshold: 0 - tab_replace: '' + tab_replace: "" ``` Prismjs is disabled by default. You should set `highlight.enable` to `false` before enabling prismjs. diff --git a/source/th/docs/tag-plugins.md b/source/th/docs/tag-plugins.md index 4cd74e069d..54d97bb95a 100644 --- a/source/th/docs/tag-plugins.md +++ b/source/th/docs/tag-plugins.md @@ -1,6 +1,7 @@ --- title: Tag Plugins --- + ปลั๊กอินแท็กจะแตกต่างกับแท็กโพสต์ ปลั๊กอินแท็กนั้นยืมมาจาก Octopress และสนับสนุนวิธีท่ีเพิ่มเนื้อหาเฉพาะไปถึงโพสต์ของตนได้อย่างรวดเร็ว @@ -88,14 +89,14 @@ code snippet Specify additional options in `option:value` format, e.g. `line_number:false first_line:5`. -Extra Options | Description | Default ---- | --- | --- -`line_number` | Show line number | `true` -`line_threshold` | Only show line numbers as long as the numbers of lines of the code block exceed such threshold. | `0` | -`highlight` | Enable code highlighting | `true` -`first_line` | Specify the first line number | `1` -`mark` | Line highlight specific line(s), each value separated by a comma. Specify number range using a dash<br>Example: `mark:1,4-7,10` will mark line 1, 4 to 7 and 10. | -`wrap` | Wrap the code block in [`<table>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table) | `true` +| Extra Options | Description | Default | +| ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| `line_number` | Show line number | `true` | +| `line_threshold` | Only show line numbers as long as the numbers of lines of the code block exceed such threshold. | `0` | +| `highlight` | Enable code highlighting | `true` | +| `first_line` | Specify the first line number | `1` | +| `mark` | Line highlight specific line(s), each value separated by a comma. Specify number range using a dash<br>Example: `mark:1,4-7,10` will mark line 1, 4 to 7 and 10. | +| `wrap` | Wrap the code block in [`<table>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table) | `true` | ### Examples @@ -145,7 +146,7 @@ _.compact([0, 1, false, 2, '', 3]); ``` {% codeblock _.compact <http://underscorejs.org/#compact> Underscore.js %} -_.compact([0, 1, false, 2, '', 3]); +\_.compact([0, 1, false, 2, '', 3]); => [1, 2, 3] {% endcodeblock %} @@ -153,9 +154,9 @@ _.compact([0, 1, false, 2, '', 3]); มันเหมือนกันกับการใช้ code block แต่จำกัดจำนวน block โดยใช้ backtick สามอัน {% raw %} -```[language] [title] [url] [link text] +``[language] [title] [url] [link text] code snippet -``` +`` {% endraw %} ## Pull Quote @@ -257,7 +258,7 @@ YouTube's cookie is not used in this mode. ## Include Posts -รวมลิงก์ของโพสต์อื่นๆเข้าไปใน block: +รวมลิงก์ของโพสต์อื่นๆเข้าไปใน block: ``` {% post_path filename %} @@ -272,7 +273,7 @@ YouTube's cookie is not used in this mode. ได้แม้ว่าโพสต์นั้นจะอยู่ใน folder `source/posts/2015-02-my-family-holiday` และมี permalink เป็น `2018/en/how-to-bake-a-cake` -แทนท่ีจะแสดงให้เห็นหัวข้อโพสต์ คุณสามารถตั้งค่าว่าอะไรของ text +แทนท่ีจะแสดงให้เห็นหัวข้อโพสต์ คุณสามารถตั้งค่าว่าอะไรของ text จะโชว์ให้เห็นได้ดัวยการตั้งค่า `post_path` ส่วน syntax ท่ีเป็น `[]()` จะไม่สนับสนุนโดย hexo ในท่ีนี่ @@ -328,32 +329,32 @@ _hexo-renderer-marked 3.1.0+ can (optionally) resolves the post's path of an ima `{% asset_img foo.jpg %}` -``` html -<img src="/2020/01/02/hello/foo.jpg"> +```html +<img src="/2020/01/02/hello/foo.jpg" /> ``` **Custom class** `{% asset_img post-image foo.jpg %}` -``` html -<img src="/2020/01/02/hello/foo.jpg" class="post-image"> +```html +<img src="/2020/01/02/hello/foo.jpg" class="post-image" /> ``` **Display size** `{% asset_img foo.jpg 500 400 %}` -``` html -<img src="/2020/01/02/hello/foo.jpg" width="500" height="400"> +```html +<img src="/2020/01/02/hello/foo.jpg" width="500" height="400" /> ``` **Title & Alt** `{% asset_img logo.svg "lorem ipsum'dolor'" %}` -``` html -<img src="/2020/01/02/hello/foo.jpg" title="lorem ipsum" alt="dolor"> +```html +<img src="/2020/01/02/hello/foo.jpg" title="lorem ipsum" alt="dolor" /> ``` ## Raw diff --git a/source/th/docs/templates.md b/source/th/docs/templates.md index 3184816089..735d556c91 100644 --- a/source/th/docs/templates.md +++ b/source/th/docs/templates.md @@ -1,43 +1,48 @@ --- title: Templates --- + template ให้คำนิยามของรูปแบบการโชว์เนื้อหาของแว็บไซต์คุณโดยตั้งค่าว่าทุกเพจของคุณต้องดูเป็นยังไง ตารางต่อไปเป็น template ท่ีเกี่ยวข้องของทุกเพจท่ีมีอยู่ในไซต์ของคุณ ธีมอันหนึ่งนั้นอย่างน้อยต้องมี template `index` รวมอยู่ด้วย {% youtube mb65bQ4iUc4 %} -Template | Page | Fallback ---- | --- | --- -`index` | Home page | -`post` | Posts | `index` -`page` | Pages | `index` -`archive` | Archives | `index` -`category` | Category archives | `archive` -`tag` | Tag archives | `archive` +| Template | Page | Fallback | +| ---------- | ----------------- | --------- | +| `index` | Home page | +| `post` | Posts | `index` | +| `page` | Pages | `index` | +| `archive` | Archives | `index` | +| `category` | Category archives | `archive` | +| `tag` | Tag archives | `archive` | ## Layouts เมื่อเพจต่างๆนั้นแชร์โครงสร้างท่ีคล้ายกัน - เช่น ถ้าสอง template นั้นล้วนมีทั้ง - header และ footer - คุณสามารถใช้ `layout` - ไปตั้งค่าให้เพจต่างๆในครั้งเดียวได้ ทุกไฟล์ layout ต้องมี variable `body` - รวมอยู่ด้วย ยกตัวอย่างเช่น: +header และ footer - คุณสามารถใช้ `layout` +ไปตั้งค่าให้เพจต่างๆในครั้งเดียวได้ ทุกไฟล์ layout ต้องมี variable `body` +รวมอยู่ด้วย ยกตัวอย่างเช่น: -``` html index.ejs +```html index.ejs index ``` -``` html layout.ejs -<!DOCTYPE html> +```html layout.ejs +<!doctype html> <html> - <body><%- body %></body> + <body> + <%- body %> + </body> </html> ``` yields: -``` html -<!DOCTYPE html> +```html +<!doctype html> <html> - <body>index</body> + <body> + index + </body> </html> ``` @@ -49,22 +54,22 @@ disable template `layout` ## Partials -partial ใช้มาเป็น component ท่ีแชว์ได้ระหว่าง template ต่างๆของคุณ +partial ใช้มาเป็น component ท่ีแชว์ได้ระหว่าง template ต่างๆของคุณ ตัวอย่างทั่วไปคือ header footer และ sidebar คุณอาจจะอยากวาง partial ใรไฟล์ท่ีแตกต่างกันเพื่อทำให้การรักษาแว็บไซต์ของคุณสะดวกขึ้น ยกตัวอย่างเช่น: -``` html partial/header.ejs +```html partial/header.ejs <h1 id="logo"><%= config.title %></h1> ``` -``` html index.ejs +```html index.ejs <%- partial('partial/header') %> <div id="content">Home page</div> ``` yields: -``` html +```html <h1 id="logo">My Site</h1> <div id="content">Home page</div> ``` @@ -72,20 +77,20 @@ yields: ## Local Variables คุณสามารถให้คำนิยามแต่ local variable ใน template และใช้ local variable -เหล่านี้ใน template อื่นๆ +เหล่านี้ใน template อื่นๆ -``` html partial/header.ejs +```html partial/header.ejs <h1 id="logo"><%= title %></h1> ``` -``` html index.ejs +```html index.ejs <%- partial('partial/header', {title: 'Hello World'}) %> <div id="content">Home page</div> ``` yields: -``` html +```html <h1 id="logo">Hello World</h1> <div id="content">Home page</div> ``` @@ -105,7 +110,7 @@ request ท่ีเพิ่มเติมขึ้นถูกเรียก caching ของ fragment จะเหมาะสมท่ีสุดกับ header footer sidebar หรือเนื้อหาคงท่ีอื่นๆ ยกตัวอย่างเช่น: -``` js +```js <%- fragment_cache('header', function(){ return '<header></header>'; }); @@ -113,7 +118,7 @@ caching ของ fragment จะเหมาะสมท่ีสุดกั แม้ว่่าการใช้ partial จะง่ายกว่า: -``` js +```js <%- partial('header', {}, {cache: true}); ``` diff --git a/source/th/docs/themes.md b/source/th/docs/themes.md index 9bace27149..5f7548c5d7 100644 --- a/source/th/docs/themes.md +++ b/source/th/docs/themes.md @@ -6,7 +6,7 @@ title: Themes การสร้างธีมของ hexo เป็นเรื่องเรียบง่าย - คุณต้องการสร้าง folder ใหม่ เพื่อเริ่มใช้ธีมของคุณ ไปแก้ไขการตั้งค่าของ `theme` ในไฟล์ `_config.yml` ธีมของ hexo จะมีโครงสร้างต่อไป: -``` plain +```plain . ├── _config.yml ├── languages @@ -15,9 +15,9 @@ title: Themes └── source ``` -### _config.yml +### \_config.yml -ไฟล์การตั้งค่าธีม Unlike the site's primary configuration file การแก้ไขไฟล์นี้แล้วไม่ต้องเปิดเซิร์ฟเวอร์ใหม่ +ไฟล์การตั้งค่าธีม Unlike the site's primary configuration file การแก้ไขไฟล์นี้แล้วไม่ต้องเปิดเซิร์ฟเวอร์ใหม่ ### languages @@ -25,9 +25,9 @@ folder ภาษา สำหรับข้อมูลเพิ่มเติ ### layout -layout folder. ใน folder นี้มีไฟล์ template ของธีม ซึ่งตั้งค่ารูปลักษณ์ของเว็บไซต์ hexo ใช้ [Nunjucks] เป็น template engine by default แต่คุณเปลี่ยนเป็น engine อื่นๆได้ เช่น [EJS], [Haml], [Jade] หรือ [Pug] hexo เลือก engine ของ template ตาม extension ของไฟล์ ยกตัวอย่างเช่น: +layout folder. ใน folder นี้มีไฟล์ template ของธีม ซึ่งตั้งค่ารูปลักษณ์ของเว็บไซต์ hexo ใช้ [Nunjucks] เป็น template engine by default แต่คุณเปลี่ยนเป็น engine อื่นๆได้ เช่น [EJS], [Haml], [Jade] หรือ [Pug] hexo เลือก engine ของ template ตาม extension ของไฟล์ ยกตัวอย่างเช่น: -``` plain +```plain layout.ejs - uses EJS layout.njk - uses Nunjucks ``` @@ -36,7 +36,7 @@ layout.njk - uses Nunjucks ### scripts -folder ของ script. hexo จะโหลดไฟล์ JavaScript ทั้งหมดใน folder นี้ในช่วง +folder ของ script. hexo จะโหลดไฟล์ JavaScript ทั้งหมดใน folder นี้ในช่วง initialization สำหรับข้อมูลเพิ่มเติม ไปดูท่ี [plugins](plugins.html) ### source @@ -58,28 +58,28 @@ hexo จะจัดการและบันทึกไฟล์ทั้ง 1. Fork [hexojs/site] 2. Clone the repository to your computer and install dependencies. - ```shell - $ git clone https://github.com/<username>/site.git - $ cd site - $ npm install - ``` + ```shell + $ git clone https://github.com/<username>/site.git + $ cd site + $ npm install + ``` 3. Edit `source/_data/themes.yml` and add your theme. For example: - ```yaml - - name: landscape - description: A brand new default theme for Hexo. - link: https://github.com/hexojs/hexo-theme-landscape - preview: http://hexo.io/hexo-theme-landscape - tags: - - official - - responsive - - widget - - two_column - - one_column - ``` - -4. Add a screenshot (with the same name as the theme) to `source/themes/screenshots`. It must be a 800*500px PNG. + ```yaml + - name: landscape + description: A brand new default theme for Hexo. + link: https://github.com/hexojs/hexo-theme-landscape + preview: http://hexo.io/hexo-theme-landscape + tags: + - official + - responsive + - widget + - two_column + - one_column + ``` + +4. Add a screenshot (with the same name as the theme) to `source/themes/screenshots`. It must be a 800\*500px PNG. 5. Push the branch. 6. Create a pull request and describe the change. diff --git a/source/th/docs/troubleshooting.md b/source/th/docs/troubleshooting.md index afac02fa05..7256a2895d 100644 --- a/source/th/docs/troubleshooting.md +++ b/source/th/docs/troubleshooting.md @@ -1,21 +1,22 @@ --- title: Troubleshooting --- -ถ้าหากว่าคุณพบเจอปัญหาเมื่อใช้ hexo + +ถ้าหากว่าคุณพบเจอปัญหาเมื่อใช้ hexo ท่ีนี่มีตารางของวิธีการแก้ปัญหาที่พบเจอบ่อยครั้ง ถ้าเกิดปัญหาท่ีไซตืนี้ไม่มี -ลองค้นหาวิธีการแก้ไขปัญหาใน [GitHub](https://github.com/hexojs/hexo/issues) -หรือ [Google Group](https://groups.google.com/group/hexo) +ลองค้นหาวิธีการแก้ไขปัญหาใน [GitHub](https://github.com/hexojs/hexo/issues) +หรือ [Google Group](https://groups.google.com/group/hexo) ## YAML Parsing Error -``` plain +```plain JS-YAML: incomplete explicit mapping pair; a key node is missed at line 18, column 29: last_updated: Last updated: %s ``` ปกคลุม string ด้วย quotation ถ้ามันมีเครื่องหมาย (:) อยู่ด้วย -``` plain +```plain JS-YAML: bad indentation of a mapping entry at line 18, column 31: last_updated:"Last updated: %s" ``` @@ -26,17 +27,17 @@ JS-YAML: bad indentation of a mapping entry at line 18, column 31: ## EMFILE Error -``` plain +```plain Error: EMFILE, too many open files ``` แม้ว่า Node.js มี I/O ท่ี non-blocking ปริมาณมากท่ีสุดของ I/O ท่ี synchronous - ยังจำกัดอยู่เนื่องด้วยระบบของ hexo คุณอาจจะพบเจอข้อผิดพลาดท่ีเป็น EMFILE - error ในเมื่อลอง generate ไฟล์เป็นจำนวนมาก - คุณอาจจะลองรันคำสั่งต่อไปเพื่อเพิ่มจำนวนของ I/O operation ท่ี synchronous - และถูกอนุญาตแล้ว +ยังจำกัดอยู่เนื่องด้วยระบบของ hexo คุณอาจจะพบเจอข้อผิดพลาดท่ีเป็น EMFILE +error ในเมื่อลอง generate ไฟล์เป็นจำนวนมาก +คุณอาจจะลองรันคำสั่งต่อไปเพื่อเพิ่มจำนวนของ I/O operation ท่ี synchronous +และถูกอนุญาตแล้ว -``` bash +```bash $ ulimit -n 10000 ``` @@ -44,7 +45,7 @@ $ ulimit -n 10000 If you encounter the following error: -``` bash +```bash $ ulimit -n 10000 ulimit: open files: cannot modify limit: Operation not permitted ``` @@ -55,13 +56,13 @@ To override the limit: 1. Add the following line to "/etc/security/limits.conf": - ``` - * - nofile 10000 +``` +* - nofile 10000 - # '*' applies to all users and '-' set both soft and hard limits - ``` +# '*' applies to all users and '-' set both soft and hard limits +``` -* The above setting may not apply in some cases, ensure "/etc/pam.d/login" and "/etc/pam.d/lightdm" have the following line. (Ignore this step if those files do not exist) +- The above setting may not apply in some cases, ensure "/etc/pam.d/login" and "/etc/pam.d/lightdm" have the following line. (Ignore this step if those files do not exist) ``` session required pam_limits.so @@ -69,9 +70,9 @@ To override the limit: 2. If you are on a [systemd-based](https://en.wikipedia.org/wiki/Systemd#Adoption) distribution, systemd may override "limits.conf". To set the limit in systemd, add the following line in "/etc/systemd/system.conf" and "/etc/systemd/user.conf": - ``` - DefaultLimitNOFILE=10000 - ``` +``` +DefaultLimitNOFILE=10000 +``` 3. Reboot @@ -83,7 +84,7 @@ To override the limit: FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory ``` -คุณเพิ่มขนาด heap memory ของ Node.js ได้ด้วยการเปลี่ยนบรรทัดแรกของ `hexo-cli` (หาไฟล์นี้ได้ด้วยคำสั่ง `which hexo`) +คุณเพิ่มขนาด heap memory ของ Node.js ได้ด้วยการเปลี่ยนบรรทัดแรกของ `hexo-cli` (หาไฟล์นี้ได้ด้วยคำสั่ง `which hexo`) ``` #!/usr/bin/env node --max_old_space_size=8192 @@ -95,7 +96,7 @@ FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory ### RPC failed -``` plain +```plain error: RPC failed; result=22, HTTP code = 403 fatal: 'username.github.io' does not appear to be a git repository @@ -124,7 +125,7 @@ fatal: 'username.github.io' does not appear to be a git repository ## Server Problems -``` plain +```plain Error: listen EADDRINUSE ``` @@ -132,13 +133,13 @@ Error: listen EADDRINUSE port เดียวกัน สำหรับการแก้ไขเรื่องนี้ลองแก้ไขการตั้งค่าของ `port`หรือเปิดเซร์ฟเวอร์ hexo ใน port ท่ีตั้งค่าโดยแท็ก`-p` -``` bash +```bash $ hexo server -p 5000 ``` ## Plugin Installation Problems -``` plain +```plain npm ERR! node-waf configure build ``` @@ -177,15 +178,15 @@ data บางอย่างอัพเดทไม่ได้ หรือ ใหม่นั้นเหมือกับไฟล์ของเวอร์ชั่นล่าสุด ถ้าเป็นอย่างนี้ กรุณาเคลีย cache และลองอีกครั้ง -``` bash +```bash $ hexo clean ``` ## No command is executed -ุถ้าคุณไม่สามารถรันคำสั่งนอกจาก `help` `init` และ `version` +ุถ้าคุณไม่สามารถรันคำสั่งนอกจาก `help` `init` และ `version` และผลท่ีส่งกลับจากคำสั่งนั้นมีแต่เนื้อหาของ `hexo help` -ปัญหานี้อาจเกิดจากการขาดแคลน `hexo` ในไฟล์ `package.json`: +ปัญหานี้อาจเกิดจากการขาดแคลน `hexo` ในไฟล์ `package.json`: ```json { @@ -200,7 +201,7 @@ $ hexo clean hexo ใช้ [Nunjucks] เพื่อ render โพสต์ (ในเวอร์ชั่นเก่าใช้ [Swig] ซึ่งมี syntax เหมือนกัน) เนื้อหาที่ห่อด้วย `{{ }}` หรือ `{% %}` อาจจะถูก parse ไม่ถูกต้องและเกิดปัญหาบ้าง เพื่อป้องกันเรื่องนี้เกิดขึ้น คุณสามารถติดตั้งปลั๊กอินแท็ก -You can skip the parsing by wrapping it with the [`raw`](/docs/tag-plugins#Raw) tag plugin, single backtick ```` `{{ }}` ```` or triple backtick. +You can skip the parsing by wrapping it with the [`raw`](/docs/tag-plugins#Raw) tag plugin, single backtick `` `{{ }}` `` or triple backtick. Alternatively, Nunjucks tags can be disabled through the renderer's option (if supported), [API](/api/renderer#Disable-Nunjucks-tags) or [front-matter](/docs/front-matter). ``` @@ -246,7 +247,7 @@ Error: watch /path/to/hexo/theme/ EMPERM จะไม่สามารถใช้ประโยชน์ได้ แต่คุณยังรันเซร์ฟเวอร์ได้ภายในสภาพแวดล้อม WSL โดย generate ไฟล์ก่อนแลัวรันเซร์ฟเวอร์แบบคงที่: -``` sh +```sh $ hexo generate $ hexo server -s ``` diff --git a/source/th/docs/variables.md b/source/th/docs/variables.md index e2ea78d9a1..4af3e14b48 100644 --- a/source/th/docs/variables.md +++ b/source/th/docs/variables.md @@ -6,15 +6,15 @@ title: Variables ### Global Variables -Variable | Description | Type ---- | --- | --- -`site` | Sitewide information. | `object`; see [Site Variables] -`page` | Page specific information and custom variables set in front-matter. | `object`; see [Page Variables] -`config` | Site configuration. | `object` (your site's _config file) -`theme` | Theme configuration. Inherits from site configuration. | `object` (your theme's _config file) -`path` | Path of current page | `string` -`url` | Full URL of current page | `string` -`env` | Environment variables | ??? +| Variable | Description | Type | +| -------- | ------------------------------------------------------------------- | ------------------------------------- | +| `site` | Sitewide information. | `object`; see [Site Variables] | +| `page` | Page specific information and custom variables set in front-matter. | `object`; see [Page Variables] | +| `config` | Site configuration. | `object` (your site's \_config file) | +| `theme` | Theme configuration. Inherits from site configuration. | `object` (your theme's \_config file) | +| `path` | Path of current page | `string` | +| `url` | Full URL of current page | `string` | +| `env` | Environment variables | ??? | {% note warn %} Lodash has been removed from global variables since Hexo 5.0.0. [You-Dont-Need-Lodash-Underscore](https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore) might be helpful for your migration. @@ -22,79 +22,79 @@ Lodash has been removed from global variables since Hexo 5.0.0. [You-Dont-Need-L ### Site Variables -Variable | Description | Type ---- | --- | --- -`site.posts` | All posts | `array` of `post` objects -`site.pages` | All pages | `array` of `page` objects -`site.categories` | All categories | `array` of ??? -`site.tags` | All tags | `array` of ??? +| Variable | Description | Type | +| ----------------- | -------------- | ------------------------- | +| `site.posts` | All posts | `array` of `post` objects | +| `site.pages` | All pages | `array` of `page` objects | +| `site.categories` | All categories | `array` of ??? | +| `site.tags` | All tags | `array` of ??? | ### Page Variables **บทความ (`page`)** -Variable | Description | Type ---- | --- | --- -`page.title` | Article title | `string` -`page.date` | Article created date | [Moment.js] object -`page.updated` | Article last updated date | [Moment.js] object -`page.comments` | Comment enabled or not | `boolean` -`page.layout` | Layout name | `string` -`page.content` | The full processed content of the article | `string` -`page.excerpt` | Article excerpt | `string` -`page.more` | Contents except article excerpt | `string` -`page.source` | The path of the source file | `string` -`page.full_source` | Full path of the source file | `string` -`page.path` | The URL of the article without root URL. We usually use `url_for(page.path)` in theme. | `string` -`page.permalink` | Full URL of the article | `string` -`page.prev` | The previous post, `null` if the post is the first post | ??? -`page.next` | The next post, `null` if the post is the last post | ??? -`page.raw` | The raw data of the article | ??? -`page.photos` | The photos of the article (Used in gallery posts) | array of ??? -`page.link` | The external link of the article (Used in link posts) | `string` - -**โพสต์ (`post`):** เหมือนกับ layout `page` แต่เพิ่ม variable ต่อไป - -Variable | Description | Type ---- | --- | --- -`page.published` | True if the post is not a draft | `boolean` -`page.categories` | All categories of the post | `array` of ??? -`page.tags` | All tags of the post | `array` of ??? +| Variable | Description | Type | +| ------------------ | -------------------------------------------------------------------------------------- | ------------------ | +| `page.title` | Article title | `string` | +| `page.date` | Article created date | [Moment.js] object | +| `page.updated` | Article last updated date | [Moment.js] object | +| `page.comments` | Comment enabled or not | `boolean` | +| `page.layout` | Layout name | `string` | +| `page.content` | The full processed content of the article | `string` | +| `page.excerpt` | Article excerpt | `string` | +| `page.more` | Contents except article excerpt | `string` | +| `page.source` | The path of the source file | `string` | +| `page.full_source` | Full path of the source file | `string` | +| `page.path` | The URL of the article without root URL. We usually use `url_for(page.path)` in theme. | `string` | +| `page.permalink` | Full URL of the article | `string` | +| `page.prev` | The previous post, `null` if the post is the first post | ??? | +| `page.next` | The next post, `null` if the post is the last post | ??? | +| `page.raw` | The raw data of the article | ??? | +| `page.photos` | The photos of the article (Used in gallery posts) | array of ??? | +| `page.link` | The external link of the article (Used in link posts) | `string` | + +**โพสต์ (`post`):** เหมือนกับ layout `page` แต่เพิ่ม variable ต่อไป + +| Variable | Description | Type | +| ----------------- | ------------------------------- | -------------- | +| `page.published` | True if the post is not a draft | `boolean` | +| `page.categories` | All categories of the post | `array` of ??? | +| `page.tags` | All tags of the post | `array` of ??? | **หน้าหลัก (`index`)** -Variable | Description | Type ---- | --- | --- -`page.per_page` | Posts displayed per page | `number` -`page.total` | Total number of pages | `number` -`page.current` | Current page number | `number` -`page.current_url` | The URL of current page | `string` -`page.posts` | Posts in this page ([Data Model](https://hexojs.github.io/warehouse/)) | `object` -`page.prev` | Previous page number. `0` if the current page is the first. | `number` -`page.prev_link` | The URL of previous page. `''` if the current page is the first. | `string` -`page.next` | Next page number. `0` if the current page is the last. | `number` -`page.next_link` | The URL of next page. `''` if the current page is the last. | `string` -`page.path` | The URL of current page without root URL. We usually use `url_for(page.path)` in theme. | `string` - -**อาไครฟ (`archive`):** เหมือนกับ layout `index` แต่เพิ่ม variable ต่อไป - -Variable | Description | Type ---- | --- | --- -`page.archive` | Equals `true` | `boolean` -`page.year` | Archive year (4-digit) | `number` -`page.month` | Archive month (2-digit without leading zeros) | `number` - -**ประเภท (`category`):** เหมือนกับ layout `index` แต่เพิ่ม variable ต่อไป - -Variable | Description | Type ---- | --- | --- -`page.category` | Category name | `string` - -**แท็ก (`tag`):** เหมือนกับ layout `index` แต่เพิ่ม variable ต่อไป - -Variable | Description | Type ---- | --- | --- -`page.tag` | Tag name | `string` +| Variable | Description | Type | +| ------------------ | --------------------------------------------------------------------------------------- | -------- | +| `page.per_page` | Posts displayed per page | `number` | +| `page.total` | Total number of pages | `number` | +| `page.current` | Current page number | `number` | +| `page.current_url` | The URL of current page | `string` | +| `page.posts` | Posts in this page ([Data Model](https://hexojs.github.io/warehouse/)) | `object` | +| `page.prev` | Previous page number. `0` if the current page is the first. | `number` | +| `page.prev_link` | The URL of previous page. `''` if the current page is the first. | `string` | +| `page.next` | Next page number. `0` if the current page is the last. | `number` | +| `page.next_link` | The URL of next page. `''` if the current page is the last. | `string` | +| `page.path` | The URL of current page without root URL. We usually use `url_for(page.path)` in theme. | `string` | + +**อาไครฟ (`archive`):** เหมือนกับ layout `index` แต่เพิ่ม variable ต่อไป + +| Variable | Description | Type | +| -------------- | --------------------------------------------- | --------- | +| `page.archive` | Equals `true` | `boolean` | +| `page.year` | Archive year (4-digit) | `number` | +| `page.month` | Archive month (2-digit without leading zeros) | `number` | + +**ประเภท (`category`):** เหมือนกับ layout `index` แต่เพิ่ม variable ต่อไป + +| Variable | Description | Type | +| --------------- | ------------- | -------- | +| `page.category` | Category name | `string` | + +**แท็ก (`tag`):** เหมือนกับ layout `index` แต่เพิ่ม variable ต่อไป + +| Variable | Description | Type | +| ---------- | ----------- | -------- | +| `page.tag` | Tag name | `string` | [Moment.js]: http://momentjs.com/ [Site Variables]: #Site-Variables diff --git a/source/th/docs/writing.md b/source/th/docs/writing.md index c1b61b02c0..993d7a2f06 100644 --- a/source/th/docs/writing.md +++ b/source/th/docs/writing.md @@ -6,22 +6,22 @@ title: Writing คุณสามรถรันคำสั่งต่อไปเพื่อสร้างโพสต์ใหม่หรือเพจใหม่: -``` bash +```bash $ hexo new [layout] <title> ``` -`post` เป็น `layout` default แต่คุณตั้งค่า layout ของตนได้โดยเปลี่ยนการตั้งค่าของ `default_layout` ใน `_config.yml` ได้ +`post` เป็น `layout` default แต่คุณตั้งค่า layout ของตนได้โดยเปลี่ยนการตั้งค่าของ `default_layout` ใน `_config.yml` ได้ ### Layout -ใน hexo มี layout ทั้งหมดสามอย่าง: `post` `page` และ `draft` ไฟล์ที่สร้างมาในต่าง layout จะอยู่ใน path ท่ีแตกต่างกัน -โพสต์ท่ีสร้างมาใหม่จะบันทึกอยู่ใน folder `source/_posts` +ใน hexo มี layout ทั้งหมดสามอย่าง: `post` `page` และ `draft` ไฟล์ที่สร้างมาในต่าง layout จะอยู่ใน path ท่ีแตกต่างกัน +โพสต์ท่ีสร้างมาใหม่จะบันทึกอยู่ใน folder `source/_posts` -Layout | Path ---- | --- -`post` | `source/_posts` -`page` | `source` -`draft` | `source/_drafts` +| Layout | Path | +| ------- | ---------------- | +| `post` | `source/_posts` | +| `page` | `source` | +| `draft` | `source/_drafts` | {% note tip Disabling layout %} If you don't want an article (post/page) to be processed with a theme, set `layout: false` in its front-matter. Refer to [this section](/docs/front-matter#Layout) for more details. @@ -29,48 +29,48 @@ If you don't want an article (post/page) to be processed with a theme, set `layo ### Filename -hexo ใช้หัวข้อของโพสต์เป็นชื่อไฟล์ คุณสามารถตั้งค่า `new_post_name` ในไฟล์ -`_config.yml` เพื่อเปลี่ยนชื่อไฟล์ default ยกตัวอย่างเช่น -`:year-:month-:day-:title.md` +hexo ใช้หัวข้อของโพสต์เป็นชื่อไฟล์ คุณสามารถตั้งค่า `new_post_name` ในไฟล์ +`_config.yml` เพื่อเปลี่ยนชื่อไฟล์ default ยกตัวอย่างเช่น +`:year-:month-:day-:title.md` จะทำให้ชื่อไฟล์มีกาลเวลาของการสร้างไฟล์รวมอยู่ด้วย คุณใช้ placeholder ต่อไปได้: -Placeholder | Description ---- | --- -`:title` | Post title (lower case, with spaces replaced by hyphens) -`:year` | Created year, e.g. `2015` -`:month` | Created month (leading zeros), e.g. `04` -`:i_month` | Created month (no leading zeros), e.g. `4` -`:day` | Created day (leading zeros), e.g. `07` -`:i_day` | Created day (no leading zeros), e.g. `7` +| Placeholder | Description | +| ----------- | -------------------------------------------------------- | +| `:title` | Post title (lower case, with spaces replaced by hyphens) | +| `:year` | Created year, e.g. `2015` | +| `:month` | Created month (leading zeros), e.g. `04` | +| `:i_month` | Created month (no leading zeros), e.g. `4` | +| `:day` | Created day (leading zeros), e.g. `07` | +| `:i_day` | Created day (no leading zeros), e.g. `7` | ### Drafts -`draft` เป็น layout อย่างหนึ่งของ hexo โพสต์ท่ีตั้งค่า layout เป็น draft -นั้นจะถูกบันทึกอยู่ใน folder `source/_drafts` คุณสามารถใช้คำสั่ง `publish` ไปย้ายไฟล์ไปถึง folder `source/_posts` ในท่ีนี้คำสั่ง `publish` คล้ายกับคำสั่ง `new` +`draft` เป็น layout อย่างหนึ่งของ hexo โพสต์ท่ีตั้งค่า layout เป็น draft +นั้นจะถูกบันทึกอยู่ใน folder `source/_drafts` คุณสามารถใช้คำสั่ง `publish` ไปย้ายไฟล์ไปถึง folder `source/_posts` ในท่ีนี้คำสั่ง `publish` คล้ายกับคำสั่ง `new` -``` bash +```bash $ hexo publish [layout] <title> ``` -draft จะไม่ render ให้เห็นในเว็บ by default คุณสามารถเพิ่มตัวเลือก `--draft` +draft จะไม่ render ให้เห็นในเว็บ by default คุณสามารถเพิ่มตัวเลือก `--draft` ให้เมื่อรัน hexo หรือ enable `render_drafts` ในไฟล์ `_config.yml` เพื่อ render draft ### Scaffolds -เมื่อสร้างโพสต์ขึ้นมา hexo จะสร้างไฟล์ตามไฟล์ท่ีมีอยู่ใน folder `scaffolds` ยกตัวอย่างเช่น: +เมื่อสร้างโพสต์ขึ้นมา hexo จะสร้างไฟล์ตามไฟล์ท่ีมีอยู่ใน folder `scaffolds` ยกตัวอย่างเช่น: -``` bash +```bash $ hexo new photo "My Gallery" ``` -เมื่อรันคำสั่งนี้ hexo จะลองหา `photo.md` ใน folder `scaffolds` และตามด้วยการสร้างโพสต์ขึ้นมา placeholder ต่อไปเป็น placeholder +เมื่อรันคำสั่งนี้ hexo จะลองหา `photo.md` ใน folder `scaffolds` และตามด้วยการสร้างโพสต์ขึ้นมา placeholder ต่อไปเป็น placeholder ท่ีตั้งค่าได้ใน scaffold: -Placeholder | Description ---- | --- -`layout` | Layout -`title` | Title -`date` | File created date +| Placeholder | Description | +| ----------- | ----------------- | +| `layout` | Layout | +| `title` | Title | +| `date` | File created date | ### Supported Formats diff --git a/source/th/index.md b/source/th/index.md index 7e2168c7bb..5a17c4abcd 100644 --- a/source/th/index.md +++ b/source/th/index.md @@ -1,7 +1,7 @@ --- layout: index description: Hexo - รวดเร็ว เรียบง่ายและมีประสิทธิภาพ กรอบบล็อกที่สนับสนุนโดย Node.js -subtitle: 'กรอบบล็อกที่รวดเร็ว เรียบง่ายและมีประสิทธิภาพ' +subtitle: "กรอบบล็อกที่รวดเร็ว เรียบง่ายและมีประสิทธิภาพ" comments: false --- @@ -42,4 +42,4 @@ comments: false <p class="intro-feature-desc">Hexo มีระบบปลั๊กอินที่มีประสิทธิภาพ โดยปลั๊กอินต่างๆ Hexo ของคุณจะสามารถสนับสนุน Jade และ CoffeeScript.</p> </div> </li> -</ul> \ No newline at end of file +</ul> diff --git a/source/themes/index.md b/source/themes/index.md index d6db114fad..95cf491687 100644 --- a/source/themes/index.md +++ b/source/themes/index.md @@ -1,3 +1,4 @@ +--- layout: plugins title: Themes data: themes diff --git a/source/zh-cn/api/box.md b/source/zh-cn/api/box.md index a8229e2633..c9dbe4b9e5 100644 --- a/source/zh-cn/api/box.md +++ b/source/zh-cn/api/box.md @@ -1,18 +1,19 @@ --- -title: Box +title: Box --- + 「Box」是 Hexo 用来处理特定文件夹中的文件的容器,在 Hexo 中有两个 Box,分别是 `hexo.source` 和 `hexo.theme`,前者用于处理 `source` 文件夹,而后者用于处理主题文件夹。 ## 加载文件 Box 提供了两种方法来加载文件:`process`, `watch`,前者用于加载文件夹内的所有文件;而后者除了执行 `process` 以外,还会继续监视文件变动。 -``` js -box.process().then(function(){ +```js +box.process().then(function () { // ... }); -box.watch().then(function(){ +box.watch().then(function () { // 之后可调用 box.unwatch(),停止监视文件 }); ``` @@ -21,7 +22,7 @@ box.watch().then(function(){ Box 提供了多种比对路径的模式,您可以以使用正则表达式(regular expression)、函数、或是 Express 风格的模式字符串,例如: -``` plain +```plain posts/:id => posts/89 posts/*path => posts/2015/title ``` @@ -32,30 +33,30 @@ posts/*path => posts/2015/title 处理器(Processor)是 Box 中非常重要的元素,它用于处理文件,您可以使用上述的路径对比来限制该处理器所要处理的文件类型。使用 `addProcessor` 来添加处理器。 -``` js -box.addProcessor('posts/:id', function(file){ +```js +box.addProcessor("posts/:id", function (file) { // }); ``` Box 在处理时会把目前处理的文件内容(`file`)传给处理器,您可以通过此参数获得该文件的数据。 -属性 | 描述 ---- | --- -`source` | 文件完整路径 -`path` | 文件相对于 Box 的路径 -`type` | 文件类型。有 `create`, `update`, `skip`, `delete`。 -`params` | 从路径对比中取得的信息 +| 属性 | 描述 | +| -------- | --------------------------------------------------- | +| `source` | 文件完整路径 | +| `path` | 文件相对于 Box 的路径 | +| `type` | 文件类型。有 `create`, `update`, `skip`, `delete`。 | +| `params` | 从路径对比中取得的信息 | Box 还提供了一些方法,让您无须手动处理文件 I/O。 -方法 | 描述 ---- | --- -`read` | 读取文件 -`readSync` | 同步读取文件 -`stat` | 读取文件状态 -`statSync` | 同步读取文件状态 -`render` | 渲染文件 -`renderSync` | 同步渲染文件 +| 方法 | 描述 | +| ------------ | ---------------- | +| `read` | 读取文件 | +| `readSync` | 同步读取文件 | +| `stat` | 读取文件状态 | +| `statSync` | 同步读取文件状态 | +| `render` | 渲染文件 | +| `renderSync` | 同步渲染文件 | [util.Pattern]: https://github.com/hexojs/hexo-util#patternrule diff --git a/source/zh-cn/api/console.md b/source/zh-cn/api/console.md index 643124e0fe..31a96709f0 100644 --- a/source/zh-cn/api/console.md +++ b/source/zh-cn/api/console.md @@ -1,21 +1,22 @@ --- title: 控制台(Console) --- + 控制台是 Hexo 与开发者之间沟通的桥梁。它注册并描述了可用的控制台命令。 ## 概要 -``` js -hexo.extend.console.register(name, desc, options, function(args){ +```js +hexo.extend.console.register(name, desc, options, function (args) { // ... }); ``` -参数 | 描述 ---- | --- -`name` | 名称 -`desc` | 描述 -`options`| 选项 +| 参数 | 描述 | +| --------- | ---- | +| `name` | 名称 | +| `desc` | 描述 | +| `options` | 选项 | 在函数中会传入 `args` 参数,此参数是使用者在终端中所传入的参数,是一个经 [Minimist] 解析的对象。 @@ -25,8 +26,10 @@ hexo.extend.console.register(name, desc, options, function(args){ 控制台的操作方法,例如: -``` js -{usage: '[layout] <title>'} +```js +{ + usage: "[layout] <title>"; +} // hexo new [layout] <title> ``` @@ -34,12 +37,12 @@ hexo.extend.console.register(name, desc, options, function(args){ 控制台各个参数的说明,例如: -``` js +```js { arguments: [ - {name: 'layout', desc: 'Post layout'}, - {name: 'title', desc: 'Post title'} - ] + { name: "layout", desc: "Post layout" }, + { name: "title", desc: "Post title" }, + ]; } ``` @@ -47,11 +50,9 @@ hexo.extend.console.register(name, desc, options, function(args){ 控制台的各个选项的说明,例如: -``` js +```js { - options: [ - {name: '-r, --replace', desc: 'Replace existing files'} - ] + options: [{ name: "-r, --replace", desc: "Replace existing files" }]; } ``` @@ -61,10 +62,14 @@ hexo.extend.console.register(name, desc, options, function(args){ ## 示例 -``` js -hexo.extend.console.register('config', 'Display configuration', function(args){ - console.log(hexo.config); -}); +```js +hexo.extend.console.register( + "config", + "Display configuration", + function (args) { + console.log(hexo.config); + }, +); ``` [Minimist]: https://github.com/minimistjs/minimist diff --git a/source/zh-cn/api/deployer.md b/source/zh-cn/api/deployer.md index 177c0169e6..b7503280a2 100644 --- a/source/zh-cn/api/deployer.md +++ b/source/zh-cn/api/deployer.md @@ -1,12 +1,13 @@ --- title: 部署器(Deployer) --- + 部署器帮助开发者将网站快速部署到远程服务器上,而无需复杂的指令。 ## 概要 -``` js -hexo.extend.deployer.register(name, function(args){ +```js +hexo.extend.deployer.register(name, function (args) { // ... }); ``` diff --git a/source/zh-cn/api/events.md b/source/zh-cn/api/events.md index 03f91797f3..babfc44fe6 100644 --- a/source/zh-cn/api/events.md +++ b/source/zh-cn/api/events.md @@ -1,6 +1,7 @@ --- title: 事件 --- + Hexo 继承了 [EventEmitter],您可以用 `on` 方法监听 Hexo 所发布的事件,也可以使用 `emit` 方法对 Hexo 发布事件,更详细的说明请参阅 Node.js 的 API。 ### deployBefore @@ -27,16 +28,16 @@ Hexo 继承了 [EventEmitter],您可以用 `on` 方法监听 Hexo 所发布的 在文章文件建立后发布。该事件返回文章参数。 -``` js -hexo.on('new', function(post){ - // +```js +hexo.on("new", function (post) { + // }); ``` -数据 | 描述 ---- | --- -`post.path` | 文章文件的完整路径 -`post.content` | 文章文件的内容 +| 数据 | 描述 | +| -------------- | ------------------ | +| `post.path` | 文章文件的完整路径 | +| `post.content` | 文章文件的内容 | ### processBefore diff --git a/source/zh-cn/api/filter.md b/source/zh-cn/api/filter.md index d993288824..81585bd909 100644 --- a/source/zh-cn/api/filter.md +++ b/source/zh-cn/api/filter.md @@ -1,11 +1,12 @@ --- title: 过滤器(Filter) --- + 过滤器用于修改特定文件,Hexo 将这些文件依序传给过滤器,而过滤器可以针对文件进行修改,这个概念借鉴自 [WordPress](http://codex.wordpress.org/Plugin_API#Filters)。 ## 概要 -``` js +```js hexo.extend.filter.register(type, function() { // User configuration const { config } = this; @@ -22,69 +23,69 @@ hexo.extend.filter.register(type, function() { ## 执行过滤器 -``` js +```js hexo.extend.filter.exec(type, data, options); hexo.extend.filter.execSync(type, data, options); ``` -选项 | 描述 ---- | --- -`context` | Context -`args` | 参数。必须为数组。 +| 选项 | 描述 | +| --------- | ------------------ | +| `context` | Context | +| `args` | 参数。必须为数组。 | `data` 会作为第一个参数传入每个过滤器,而您可以在过滤器中通过返回值改变下一个过滤器中的 `data`,如果什么都没有返回的话则会保持原本的 `data`。您还可以使用 `args` 指定过滤器的其他参数。举例来说: -``` js -hexo.extend.filter.register('test', function(data, arg1, arg2){ +```js +hexo.extend.filter.register("test", function (data, arg1, arg2) { // data === 'some data' // arg1 === 'foo' // arg2 === 'bar' - - return 'something'; + + return "something"; }); -hexo.extend.filter.register('test', function(data, arg1, arg2){ +hexo.extend.filter.register("test", function (data, arg1, arg2) { // data === 'something' }); -hexo.extend.filter.exec('test', 'some data', { - args: ['foo', 'bar'] +hexo.extend.filter.exec("test", "some data", { + args: ["foo", "bar"], }); ``` 您也可以使用以下方法来执行过滤器: -``` js +```js hexo.execFilter(type, data, options); hexo.execFilterSync(type, data, options); ``` ## 移除过滤器 -``` js +```js hexo.extend.filter.unregister(type, filter); ``` **示例** -``` js +```js // 移除一个使用具名函数注册的过滤器 const filterFn = (data) => { - data = 'something'; + data = "something"; return data; }; -hexo.extend.filter.register('example', filterFn); +hexo.extend.filter.register("example", filterFn); -hexo.extend.filter.unregister('example', filterFn); +hexo.extend.filter.unregister("example", filterFn); ``` -``` js +```js // 移除一个使用 CommonJS 模块注册的过滤器 -hexo.extend.filter.register('example', require('path/to/filter')); +hexo.extend.filter.register("example", require("path/to/filter")); -hexo.extend.filter.unregister('example', require('path/to/filter')); +hexo.extend.filter.unregister("example", require("path/to/filter")); ``` ## 过滤器列表 @@ -97,8 +98,8 @@ hexo.extend.filter.unregister('example', require('path/to/filter')); 举例来说,把标题转为小写: -``` js -hexo.extend.filter.register('before_post_render', function(data){ +```js +hexo.extend.filter.register("before_post_render", function (data) { data.title = data.title.toLowerCase(); return data; }); @@ -110,9 +111,12 @@ hexo.extend.filter.register('before_post_render', function(data){ 举例来说,把 `@username` 取代为 Twitter 的开发者链接。 -``` js -hexo.extend.filter.register('after_post_render', function(data){ - data.content = data.content.replace(/@(\d+)/, '<a href="http://twitter.com/$1">#$1</a>'); +```js +hexo.extend.filter.register("after_post_render", function (data) { + data.content = data.content.replace( + /@(\d+)/, + '<a href="http://twitter.com/$1">#$1</a>', + ); return data; }); ``` @@ -121,8 +125,8 @@ hexo.extend.filter.register('after_post_render', function(data){ 在 Hexo 即将结束时执行,也就是在 `hexo.exit` 被调用后执行。 -``` js -hexo.extend.filter.register('before_exit', function(){ +```js +hexo.extend.filter.register("before_exit", function () { // ... }); ``` @@ -131,8 +135,8 @@ hexo.extend.filter.register('before_exit', function(){ 在生成器解析前执行。 -``` js -hexo.extend.filter.register('before_generate', function(){ +```js +hexo.extend.filter.register("before_generate", function () { // ... }); ``` @@ -141,8 +145,8 @@ hexo.extend.filter.register('before_generate', function(){ 在生成器解析后执行。 -``` js -hexo.extend.filter.register('after_generate', function(){ +```js +hexo.extend.filter.register("after_generate", function () { // ... }); ``` @@ -153,8 +157,8 @@ hexo.extend.filter.register('after_generate', function(){ 举例来说,在模板的局部变量中新增当前时间: -``` js -hexo.extend.filter.register('template_locals', function(locals){ +```js +hexo.extend.filter.register("template_locals", function (locals) { locals.now = Date.now(); return locals; }); @@ -164,8 +168,8 @@ hexo.extend.filter.register('template_locals', function(locals){ 在 Hexo 初始化完成后执行,也就是在 `hexo.init` 执行完成后执行。 -``` js -hexo.extend.filter.register('after_init', function(){ +```js +hexo.extend.filter.register("after_init", function () { // ... }); ``` @@ -174,8 +178,8 @@ hexo.extend.filter.register('after_init', function(){ 用来决定新建文章的路径,在建立文章时执行。 -``` js -hexo.extend.filter.register('new_post_path', function(data, replace){ +```js +hexo.extend.filter.register("new_post_path", function (data, replace) { // ... }); ``` @@ -184,8 +188,8 @@ hexo.extend.filter.register('new_post_path', function(data, replace){ 用来决定文章的永久链接。 -``` js -hexo.extend.filter.register('post_permalink', function(data){ +```js +hexo.extend.filter.register("post_permalink", function (data) { // ... }); ``` @@ -200,10 +204,10 @@ hexo.extend.filter.register('post_permalink', function(data){ 举例来说,在响应头中新增 `X-Powered-By: Hexo`。 -``` js -hexo.extend.filter.register('server_middleware', function(app){ - app.use(function(req, res, next){ - res.setHeader('X-Powered-By', 'Hexo'); +```js +hexo.extend.filter.register("server_middleware", function (app) { + app.use(function (req, res, next) { + res.setHeader("X-Powered-By", "Hexo"); next(); }); }); diff --git a/source/zh-cn/api/generator.md b/source/zh-cn/api/generator.md index f50ca72da6..bf43ba9d4f 100644 --- a/source/zh-cn/api/generator.md +++ b/source/zh-cn/api/generator.md @@ -1,40 +1,40 @@ --- title: 生成器(Generator) --- + 生成器根据处理后的原始文件建立路由。 ## 概要 -``` js -hexo.extend.generator.register(name, function(locals){ -}); +```js +hexo.extend.generator.register(name, function (locals) {}); ``` `locals` 参数会被传递到此函数,其中包含 [网站变量](../docs/variables.html#网站变量),请尽量利用此参数取得网站数据,避免直接访问数据库。 ## 更新路由 -``` js -hexo.extend.generator.register('test', function(locals){ +```js +hexo.extend.generator.register("test", function (locals) { // Object return { - path: 'foo', - data: 'foo' + path: "foo", + data: "foo", }; - + // Array return [ - {path: 'foo', data: 'foo'}, - {path: 'bar', data: 'bar'} + { path: "foo", data: "foo" }, + { path: "bar", data: "bar" }, ]; }); ``` -属性 | 描述 ---- | --- -`path` | 路径。不可包含开头的 `/`。 -`data` | 数据 -`layout` | 布局。指定用于渲染的模板,可为字符串或数组,如果省略此属性的话则会直接输出 `data`。 +| 属性 | 描述 | +| -------- | ----------------------------------------------------------------------------------- | +| `path` | 路径。不可包含开头的 `/`。 | +| `data` | 数据 | +| `layout` | 布局。指定用于渲染的模板,可为字符串或数组,如果省略此属性的话则会直接输出 `data`。 | 在原始文件更新时,Hexo 会执行所有生成器并重建路由,**请直接回传数据,不要直接操作路由**。 @@ -46,13 +46,13 @@ hexo.extend.generator.register('test', function(locals){ 然后,设置 `layout` 属性好让 Hexo 使用主题模板来渲染,在此例中同时设定了两个布局,当 `archive` 布局不存在时,会继续尝试 `index` 布局。 -``` js -hexo.extend.generator.register('archive', function(locals){ +```js +hexo.extend.generator.register("archive", function (locals) { return { - path: 'archives/index.html', + path: "archives/index.html", data: locals.posts, - layout: ['archive', 'index'] - } + layout: ["archive", "index"], + }; }); ``` @@ -60,14 +60,14 @@ hexo.extend.generator.register('archive', function(locals){ 您可以通过 [hexo-pagination] 这个方便的官方工具来轻松建立分页归档。 -``` js -var pagination = require('hexo-pagination'); +```js +var pagination = require("hexo-pagination"); -hexo.extend.generator.register('archive', function(locals){ - return pagination('archives/index.html', locals.posts, { +hexo.extend.generator.register("archive", function (locals) { + return pagination("archives/index.html", locals.posts, { perPage: 10, - layout: ['archive', 'index'], - data: {} + layout: ["archive", "index"], + data: {}, }); }); ``` @@ -76,13 +76,13 @@ hexo.extend.generator.register('archive', function(locals){ 遍历 `locals.posts` 中的所有文章并生成所有文章的路由。 -``` js -hexo.extend.generator.register('post', function(locals){ - return locals.posts.map(function(post){ +```js +hexo.extend.generator.register("post", function (locals) { + return locals.posts.map(function (post) { return { path: post.path, data: post, - layout: 'post' + layout: "post", }; }); }); @@ -92,15 +92,15 @@ hexo.extend.generator.register('post', function(locals){ 这次我们不明确返回数据,而是将 `data` 设置为一个函数,这样路由只会在需要时才会构建 `fs.ReadStream`。 -``` js -var fs = require('hexo-fs'); +```js +var fs = require("hexo-fs"); -hexo.extend.generator.register('asset', function(locals){ +hexo.extend.generator.register("asset", function (locals) { return { - path: 'file.txt', - data: function(){ - return fs.createReadStream('path/to/file.txt') - } + path: "file.txt", + data: function () { + return fs.createReadStream("path/to/file.txt"); + }, }; }); ``` diff --git a/source/zh-cn/api/helper.md b/source/zh-cn/api/helper.md index edd012bc87..6c287ee0de 100644 --- a/source/zh-cn/api/helper.md +++ b/source/zh-cn/api/helper.md @@ -1,26 +1,28 @@ --- title: 辅助函数(Helper) --- + 辅助函数帮助您在模板中快速插入内容,建议您把复杂的代码放在辅助函数而非模板中。 辅助函数不能从 `source` 的文件中访问。 + ## 概要 -``` js -hexo.extend.helper.register(name, function(){ +```js +hexo.extend.helper.register(name, function () { // ... }); ``` ## 示例 -``` js -hexo.extend.helper.register('js', function(path){ +```js +hexo.extend.helper.register("js", function (path) { return '<script src="' + path + '"></script>'; }); ``` -``` js +```js <%- js('script.js') %> // <script src="script.js"></script> ``` @@ -35,8 +37,8 @@ hexo.extend.helper.register('js', function(path){ 所有的辅助函数都在同一个上下文中执行。例如,在一个自定义的辅助函数中使用 [`url_for()`](/zh-cn/docs/helpers#url-for): -``` js -hexo.extend.helper.register('lorem', function(path) { +```js +hexo.extend.helper.register("lorem", function (path) { return '<script src="' + this.url_for(path) + '"></script>'; }); ``` @@ -45,6 +47,6 @@ hexo.extend.helper.register('lorem', function(path) { `hexo.extend.helper.get` 会返回一个指定名字的 helper,但是你还需要一个 `bind(hexo)`,就像这样: -``` js -const url_for = hexo.extend.helper.get('url_for').bind(hexo); +```js +const url_for = hexo.extend.helper.get("url_for").bind(hexo); ``` diff --git a/source/zh-cn/api/index.md b/source/zh-cn/api/index.md index 018ac4176f..e0bbf77f17 100644 --- a/source/zh-cn/api/index.md +++ b/source/zh-cn/api/index.md @@ -1,6 +1,7 @@ --- title: API --- + 本文件提供您更丰富的 API 信息,使您更容易修改 Hexo 源代码或编写插件。如果您只是想查询 Hexo 的基本使用方法,请参阅 [文档](../docs/)。 在开始之前,请注意本文件仅适用于 Hexo 3 及以上版本。 @@ -9,22 +10,22 @@ title: API 首先,我们必须建立一个 Hexo 实例(instance),第一个参数是网站的根目录,也就是 `base_dir`,而第二个参数则是初始化的选项。接着执行 `init` 方法后,Hexo 会加载插件及配置文件。 -``` js -var Hexo = require('hexo'); +```js +var Hexo = require("hexo"); var hexo = new Hexo(process.cwd(), {}); -hexo.init().then(function(){ +hexo.init().then(function () { // ... }); ``` -参数 | 描述 | 默认值 ---- | --- | --- -`debug` | 开启调试模式。在终端中显示调试信息,并在根目录中存储 `debug.log` 日志文件。| `false` -`safe` | 开启安全模式。不加载任何插件。| `false` -`silent` | 开启安静模式。不在终端中显示任何信息。| `false` -`config` | 指定配置文件的路径。| `_config.yml` -`draft` / `drafts`| 是否将草稿加入到文章列表中。<br>例如在 `hexo.locals.get('posts')` 中获取草稿内容 | _config.yml 中 `render_drafts` 的值 +| 参数 | 描述 | 默认值 | +| ------------------ | -------------------------------------------------------------------------------- | ------------------------------------ | +| `debug` | 开启调试模式。在终端中显示调试信息,并在根目录中存储 `debug.log` 日志文件。 | `false` | +| `safe` | 开启安全模式。不加载任何插件。 | `false` | +| `silent` | 开启安静模式。不在终端中显示任何信息。 | `false` | +| `config` | 指定配置文件的路径。 | `_config.yml` | +| `draft` / `drafts` | 是否将草稿加入到文章列表中。<br>例如在 `hexo.locals.get('posts')` 中获取草稿内容 | \_config.yml 中 `render_drafts` 的值 | ## 加载文件 @@ -32,12 +33,12 @@ Hexo 提供了两种方法来加载文件:`load`, `watch`,前者用于加载 这两个方法实际上所做的,就是加载文件列表,并把文件传给相对应的处理器(Processor),当文件全部处理完毕后,就会执行生成器(Generator)来建立路由。 -``` js -hexo.load().then(function(){ +```js +hexo.load().then(function () { // ... }); -hexo.watch().then(function(){ +hexo.watch().then(function () { // 之后可以调用 hexo.unwatch(),停止监视文件 }); ``` @@ -46,8 +47,8 @@ hexo.watch().then(function(){ 您可以通过 `call` 方法来调用控制台(Console),第一个参数是控制台的名称,而第二个参数是选项——根据不同控制台有所不同。 -``` js -hexo.call('generate', {}).then(function(){ +```js +hexo.call("generate", {}).then(function () { // ... }); ``` @@ -56,10 +57,13 @@ hexo.call('generate', {}).then(function(){ 无论控制台命令完成与否,都应调用 `exit` 方法。这样 Hexo 就能优雅地退出,并完成保存数据库等重要工作。 -``` js -hexo.call('generate').then(function(){ - return hexo.exit(); -}).catch(function(err){ - return hexo.exit(err); -}); +```js +hexo + .call("generate") + .then(function () { + return hexo.exit(); + }) + .catch(function (err) { + return hexo.exit(err); + }); ``` diff --git a/source/zh-cn/api/injector.md b/source/zh-cn/api/injector.md index 3db8630790..d07af697ac 100644 --- a/source/zh-cn/api/injector.md +++ b/source/zh-cn/api/injector.md @@ -7,7 +7,7 @@ title: 注入器(Injector) ## 概要 ```js -hexo.extend.injector.register(entry, value, to) +hexo.extend.injector.register(entry, value, to); ``` ### entry `<string>` @@ -38,24 +38,34 @@ hexo.extend.injector.register(entry, value, to) - `tag`: 只注入到标签页面(`is_tag()` 为 `true` 的页面) - 或是其他自定义 layout 名称,自定义 layout 参见 [写作 - 布局(Layout)](/zh-cn/docs/writing#布局(Layout)) ----- +--- 注入器还有一些内部函数,如果你要使用它们,请参考 [hexojs/hexo#4049](https://github.com/hexojs/hexo/pull/4049)。 ## 示例 ```js -const css = hexo.extend.helper.get('css').bind(hexo); -const js = hexo.extend.helper.get('js').bind(hexo); - -hexo.extend.injector.register('head_end', () => { - return css('https://cdn.jsdelivr.net/npm/aplayer@1.10.1/dist/APlayer.min.css'); -}, 'music'); - -hexo.extend.injector.register('body_end', '<script src="https://cdn.jsdelivr.net/npm/aplayer@1.10.1/dist/APlayer.min.js">', 'music'); - -hexo.extend.injector.register('body_end', () => { - return js('/js/jquery.js'); +const css = hexo.extend.helper.get("css").bind(hexo); +const js = hexo.extend.helper.get("js").bind(hexo); + +hexo.extend.injector.register( + "head_end", + () => { + return css( + "https://cdn.jsdelivr.net/npm/aplayer@1.10.1/dist/APlayer.min.css", + ); + }, + "music", +); + +hexo.extend.injector.register( + "body_end", + '<script src="https://cdn.jsdelivr.net/npm/aplayer@1.10.1/dist/APlayer.min.js">', + "music", +); + +hexo.extend.injector.register("body_end", () => { + return js("/js/jquery.js"); }); ``` @@ -67,10 +77,10 @@ hexo.extend.injector.register('body_end', () => { 1. -``` js -const css = hexo.extend.helper.get('css').bind(hexo); +```js +const css = hexo.extend.helper.get("css").bind(hexo); -hexo.extend.injector.register('head_end', () => { +hexo.extend.injector.register("head_end", () => { const { cssPath } = hexo.config.fooPlugin; return css(cssPath); }); @@ -78,23 +88,23 @@ hexo.extend.injector.register('head_end', () => { 2. -``` js index.js +```js index.js /* global hexo */ -hexo.extend.injector.register('head_end', require('./lib/inject').bind(hexo)) +hexo.extend.injector.register("head_end", require("./lib/inject").bind(hexo)); ``` -``` js lib/inject.js +```js lib/inject.js module.exports = function () { - const css = this.extend.helper.get('css'); + const css = this.extend.helper.get("css"); const { cssPath } = this.config.fooPlugin; return css(cssPath); -} +}; ``` -``` js lib/inject.js +```js lib/inject.js function injectFn() { - const css = this.extend.helper.get('css'); + const css = this.extend.helper.get("css"); const { cssPath } = this.config.fooPlugin; return css(cssPath); } @@ -104,23 +114,23 @@ module.exports = injectFn; 3. -``` js index.js +```js index.js /* global hexo */ -hexo.extend.injector.register('head_end', require('./lib/inject')(hexo)) +hexo.extend.injector.register("head_end", require("./lib/inject")(hexo)); ``` -``` js lib/inject.js +```js lib/inject.js module.exports = (hexo) => () => { - const css = hexo.extend.helper.get('css').bind(hexo); + const css = hexo.extend.helper.get("css").bind(hexo); const { cssPath } = hexo.config.fooPlugin; return css(cssPath); }; ``` -``` js lib/inject.js +```js lib/inject.js const injectFn = (hexo) => { - const css = hexo.extend.helper.get('css').bind(hexo); + const css = hexo.extend.helper.get("css").bind(hexo); const { cssPath } = hexo.config.fooPlugin; return css(cssPath); }; diff --git a/source/zh-cn/api/locals.md b/source/zh-cn/api/locals.md index 8943373136..d759e5d118 100644 --- a/source/zh-cn/api/locals.md +++ b/source/zh-cn/api/locals.md @@ -1,26 +1,27 @@ --- title: 局部变量 --- + 局部变量用于模版渲染,也就是模版中的 `site` 变量。 ## 默认变量 -变量 | 描述 ---- | --- -`posts` | 所有文章 -`pages` | 所有分页 -`categories` | 所有分类 -`tags` | 所有标签 +| 变量 | 描述 | +| ------------ | -------- | +| `posts` | 所有文章 | +| `pages` | 所有分页 | +| `categories` | 所有分类 | +| `tags` | 所有标签 | ## 获取变量 -``` js -hexo.locals.get('posts') +```js +hexo.locals.get("posts"); ``` ## 设置变量 -``` js +```js hexo.locals.set('posts', function(){ return ... }); @@ -28,18 +29,18 @@ hexo.locals.set('posts', function(){ ## 移除变量 -``` js -hexo.locals.remove('posts'); +```js +hexo.locals.remove("posts"); ``` ## 获取所有变量 -``` js +```js hexo.locals.toObject(); ``` ## 清除缓存 -``` js +```js hexo.locals.invalidate(); ``` diff --git a/source/zh-cn/api/migrator.md b/source/zh-cn/api/migrator.md index 880de2f507..cd71da4fe7 100644 --- a/source/zh-cn/api/migrator.md +++ b/source/zh-cn/api/migrator.md @@ -1,12 +1,13 @@ --- title: 迁移器(Migrator) --- + 迁移器帮助开发者从其他系统迁移到 Hexo。 ## 概要 -``` js -hexo.extend.migrator.register(name, function(args){ +```js +hexo.extend.migrator.register(name, function (args) { // ... }); ``` diff --git a/source/zh-cn/api/posts.md b/source/zh-cn/api/posts.md index 6fdc6838c2..a40ae10380 100644 --- a/source/zh-cn/api/posts.md +++ b/source/zh-cn/api/posts.md @@ -1,55 +1,56 @@ --- title: 文章 --- + ## 新建文章 -``` js +```js hexo.post.create(data, replace); ``` -参数 | 描述 ---- | --- -`data` | 数据 -`replace` | 替换现有文件 +| 参数 | 描述 | +| --------- | ------------ | +| `data` | 数据 | +| `replace` | 替换现有文件 | 您可以在 `data` 中指定文章的属性,除了以下属性之外,其他属性也会被加到 front-matter 中。 -属性 | 描述 ---- | --- -`title` | 标题 -`slug` | 网址 -`layout` | 布局。默认为 `default_layout` 参数。 -`path` | 路径。默认会根据 `new_post_path` 参数创建文章路径。 -`date` | 日期。默认为当前时间。 +| 属性 | 描述 | +| -------- | --------------------------------------------------- | +| `title` | 标题 | +| `slug` | 网址 | +| `layout` | 布局。默认为 `default_layout` 参数。 | +| `path` | 路径。默认会根据 `new_post_path` 参数创建文章路径。 | +| `date` | 日期。默认为当前时间。 | ## 发布草稿 -``` js +```js hexo.post.publish(data, replace); ``` -参数 | 描述 ---- | --- -`data` | 数据 -`replace` | 替换现有文件 +| 参数 | 描述 | +| --------- | ------------ | +| `data` | 数据 | +| `replace` | 替换现有文件 | 您可以在 `data` 中指定文章的属性,除了以下的属性之外,其他属性也会被加到 front-matter 中。 -属性 | 描述 ---- | --- -`slug` | 文件名称(必须) -`layout` | 布局。默认为 `default_layout` 参数。 +| 属性 | 描述 | +| -------- | ------------------------------------ | +| `slug` | 文件名称(必须) | +| `layout` | 布局。默认为 `default_layout` 参数。 | ## 渲染 -``` js +```js hexo.post.render(source, data); ``` -参数 | 描述 ---- | --- -`source` | 文件的完整路径(可忽略) -`data` | 数据 +| 参数 | 描述 | +| -------- | ------------------------ | +| `source` | 文件的完整路径(可忽略) | +| `data` | 数据 | 数据中必须包含 `content` 属性,如果没有的话,Hexo 会尝试读取原始文件。此函数的执行顺序为: diff --git a/source/zh-cn/api/processor.md b/source/zh-cn/api/processor.md index 923e5e23c7..ca368e7e43 100644 --- a/source/zh-cn/api/processor.md +++ b/source/zh-cn/api/processor.md @@ -1,13 +1,13 @@ --- title: 处理器(Processor) --- + 处理器用于处理 `source` 文件夹内的原始文件。 ## 概要 -``` js -hexo.extend.processor.register(rule, function(file){ -}); +```js +hexo.extend.processor.register(rule, function (file) {}); ``` 完整说明请参考 [Box](box.html)。 diff --git a/source/zh-cn/api/renderer.md b/source/zh-cn/api/renderer.md index 99ecd0e54e..ee824fd7bd 100644 --- a/source/zh-cn/api/renderer.md +++ b/source/zh-cn/api/renderer.md @@ -1,71 +1,86 @@ --- title: 渲染引擎(Renderer) --- + 渲染引擎用于渲染内容。 ## 概要 -``` js -hexo.extend.renderer.register(name, output, function(data, options){ - // ... -}, sync); +```js +hexo.extend.renderer.register( + name, + output, + function (data, options) { + // ... + }, + sync, +); ``` -参数 | 描述 ---- | --- -`name` | 输入的扩展名(小写,不含开头的 `.`) -`output` | 输出的扩展名(小写,不含开头的 `.`) -`sync` | 同步模式 +| 参数 | 描述 | +| -------- | ------------------------------------ | +| `name` | 输入的扩展名(小写,不含开头的 `.`) | +| `output` | 输出的扩展名(小写,不含开头的 `.`) | +| `sync` | 同步模式 | 渲染函数中会传入三个参数: -参数 | 描述 ---- | --- -`data` | 包含两个属性:文件路径 `path` 和文件内容 `text`。`path` 不一定存在。 -`option` | 选项 -`callback` | 包含两个参数 `err`, `value` 的回调函数 +| 参数 | 描述 | +| ---------- | -------------------------------------------------------------------- | +| `data` | 包含两个属性:文件路径 `path` 和文件内容 `text`。`path` 不一定存在。 | +| `option` | 选项 | +| `callback` | 包含两个参数 `err`, `value` 的回调函数 | ## 示例 ### 异步模式 -``` js -var stylus = require('stylus'); +```js +var stylus = require("stylus"); // Callback -hexo.extend.renderer.register('styl', 'css', function(data, options, callback){ - stylus(data.text).set('filename', data.path).render(callback); -}); +hexo.extend.renderer.register( + "styl", + "css", + function (data, options, callback) { + stylus(data.text).set("filename", data.path).render(callback); + }, +); // Promise -hexo.extend.renderer.register('styl', 'css', function(data, options){ - return new Promise(function(resolve, reject){ - resolve('test'); +hexo.extend.renderer.register("styl", "css", function (data, options) { + return new Promise(function (resolve, reject) { + resolve("test"); }); }); ``` ### 同步模式 -``` js -var ejs = require('ejs'); - -hexo.extend.renderer.register('ejs', 'html', function(data, options){ - options.filename = data.path; - return ejs.render(data.text, options); -}, true); +```js +var ejs = require("ejs"); + +hexo.extend.renderer.register( + "ejs", + "html", + function (data, options) { + options.filename = data.path; + return ejs.render(data.text, options); + }, + true, +); ``` ### 禁用 Nunjucks 标签 Nunjucks 标签 `{{ }}` 或 `{% %}` (被 [标签插件](/zh-cn/docs/tag-plugins) 所使用) 默认会被处理,想要禁用: -``` js +```js function lessFn(data, options) { // do something } -lessFn.disableNunjucks = true +lessFn.disableNunjucks = true; -hexo.extend.renderer.register('less', 'css', lessFn); +hexo.extend.renderer.register("less", "css", lessFn); ``` diff --git a/source/zh-cn/api/rendering.md b/source/zh-cn/api/rendering.md index 5c51bf60d2..431d12676c 100644 --- a/source/zh-cn/api/rendering.md +++ b/source/zh-cn/api/rendering.md @@ -1,14 +1,15 @@ --- title: 渲染 --- + 在 Hexo 中,有两个方法可用于渲染文件或字符串,分别是异步的 `hexo.render.render` 和同步的 `hexo.render.renderSync`,这两个方法的使用方式十分类似,因此下文仅以异步的 `hexo.render.render` 为例。 ## 渲染字符串 在渲染字符串时,您必须指定 `engine`,如此一来 Hexo 才知道该使用哪个渲染引擎来渲染。 -``` js -hexo.render.render({text: 'example', engine: 'swig'}).then(function(result){ +```js +hexo.render.render({ text: "example", engine: "swig" }).then(function (result) { // ... }); ``` @@ -17,8 +18,8 @@ hexo.render.render({text: 'example', engine: 'swig'}).then(function(result){ 在渲染文件时,您无须指定 `engine`,Hexo 会自动根据扩展名猜测所要使用的渲染引擎,当然您也可以使用 `engine` 指定。 -``` js -hexo.render.render({path: 'path/to/file.swig'}).then(function(result){ +```js +hexo.render.render({ path: "path/to/file.swig" }).then(function (result) { // ... }); ``` @@ -27,8 +28,8 @@ hexo.render.render({path: 'path/to/file.swig'}).then(function(result){ 在渲染时,您可以向第二个参数中传入参数。 -``` js -hexo.render.render({text: ''}, {foo: 'foo'}).then(function(result){ +```js +hexo.render.render({ text: "" }, { foo: "foo" }).then(function (result) { // ... }); ``` @@ -37,10 +38,10 @@ hexo.render.render({text: ''}, {foo: 'foo'}).then(function(result){ 在渲染完成后,Hexo 会自动执行相对应的 `after_render` 过滤器,举例来说,我们可以通过这个功能实现 JavaScript 的压缩。 -``` js -var UglifyJS = require('uglify-js'); +```js +var UglifyJS = require("uglify-js"); -hexo.extend.filter.register('after_render:js', function(str, data){ +hexo.extend.filter.register("after_render:js", function (str, data) { var result = UglifyJS.minify(str); return result.code; }); @@ -50,30 +51,30 @@ hexo.extend.filter.register('after_render:js', function(str, data){ 您可以通过 `isRenderable` 或 `isRenderableSync` 两个方法检查文件路径是否可以被渲染,只有在相对应的渲染器(renderer)已注册的情况下才会返回 true。 -``` js -hexo.render.isRenderable('layout.swig') // true -hexo.render.isRenderable('image.png') // false +```js +hexo.render.isRenderable("layout.swig"); // true +hexo.render.isRenderable("image.png"); // false ``` ## 获取文件的输出扩展名 您可以通过 `getOutput` 方法取得文件路径输出后的扩展名,如果文件无法渲染,则会返回空字符串。 -``` js -hexo.render.getOutput('layout.swig') // html -hexo.render.getOutput('image.png') // ''' +```js +hexo.render.getOutput("layout.swig"); // html +hexo.render.getOutput("image.png"); // ''' ``` ## 禁用 Nunjucks 标签 如果你没有使用 [标签插件](/zh-cn/docs/tag-plugins) 并且想要在你的文章中使用 `{{ }}` 或 `{% %}` 而不使用 [转义](/zh-cn/docs/troubleshooting#转义(Escape)内容), 你可以通过以下方式在现有的渲染器中禁用对 Nunjucks 标签的处理: -``` js +```js // 以下示例仅适用于".md "文件扩展名 // 您可能需要覆盖其他扩展名,例如'.markdown'、'.mkd'等 -const renderer = hexo.render.renderer.get('md') +const renderer = hexo.render.renderer.get("md"); if (renderer) { - renderer.disableNunjucks = true - hexo.extend.renderer.register('md', 'html', renderer) + renderer.disableNunjucks = true; + hexo.extend.renderer.register("md", "html", renderer); } ``` diff --git a/source/zh-cn/api/router.md b/source/zh-cn/api/router.md index c68dbd5ad9..00e3efdaeb 100644 --- a/source/zh-cn/api/router.md +++ b/source/zh-cn/api/router.md @@ -1,15 +1,16 @@ --- title: 路由 --- + 路由存储了网站中所用到的所有路径。 ## 获取路径 `get` 方法会传回一个 [Stream],例如把该路径的数据存储到某个指定位置。 -``` js -var data = hexo.route.get('index.html'); -var dest = fs.createWriteStream('somewhere'); +```js +var data = hexo.route.get("index.html"); +var dest = fs.createWriteStream("somewhere"); data.pipe(dest); ``` @@ -18,32 +19,32 @@ data.pipe(dest); 您可以在 `set` 方法中使用字符串、[Buffer] 或函数,如下: -``` js +```js // String -hexo.route.set('index.html', 'index') +hexo.route.set("index.html", "index"); // Buffer -hexo.route.set('index.html', new Buffer('index')); +hexo.route.set("index.html", new Buffer("index")); // Function (Promise) -hexo.route.set('index.html', function(){ - return new Promise(function(resolve, reject){ - resolve('index'); +hexo.route.set("index.html", function () { + return new Promise(function (resolve, reject) { + resolve("index"); }); }); // Function (Callback) -hexo.route.set('index.html', function(callback){ - callback(null, 'index'); +hexo.route.set("index.html", function (callback) { + callback(null, "index"); }); ``` 您还可以设置该路径是否更新,这样在生成文件时便能忽略未更动的文件,加快生成时间。 -``` js -hexo.route.set('index.html', { - data: 'index', - modified: false +```js +hexo.route.set("index.html", { + data: "index", + modified: false, }); // hexo.route.isModified('index.html') => false @@ -51,13 +52,13 @@ hexo.route.set('index.html', { ## 移除路径 -``` js -hexo.route.remove('index.html'); +```js +hexo.route.remove("index.html"); ``` ## 获得路由表 -``` js +```js hexo.route.list(); ``` @@ -65,8 +66,8 @@ hexo.route.list(); `format` 方法可将字符串转为合法的路径。 -``` js -hexo.route.format('archives/'); +```js +hexo.route.format("archives/"); // archives/index.html ``` diff --git a/source/zh-cn/api/scaffolds.md b/source/zh-cn/api/scaffolds.md index 4e607e757e..8ae40a5ccc 100644 --- a/source/zh-cn/api/scaffolds.md +++ b/source/zh-cn/api/scaffolds.md @@ -1,20 +1,21 @@ --- title: 脚手架(Scaffold) --- + ## 获得脚手架 -``` js +```js hexo.scaffold.get(name); ``` ## 设置脚手架 -``` js +```js hexo.scaffold.set(name, content); ``` ## 移除脚手架 -``` js +```js hexo.scaffold.remove(name); ``` diff --git a/source/zh-cn/api/tag.md b/source/zh-cn/api/tag.md index b6c5b18fe7..2633223838 100644 --- a/source/zh-cn/api/tag.md +++ b/source/zh-cn/api/tag.md @@ -1,13 +1,13 @@ --- title: 标签插件(Tag) --- + 标签插件帮助开发者在文章中快速插入内容。 ## 概要 -``` js -hexo.extend.tag.register(name, function(args, content){ -}, options); +```js +hexo.extend.tag.register(name, function (args, content) {}, options); ``` 标签函数会传入两个参数:`args` 和 `content`,前者代表开发者在使用标签插件时传入的参数,而后者则是标签插件所覆盖的内容。 @@ -18,22 +18,22 @@ hexo.extend.tag.register(name, function(args, content){ 使用 `unregister()` 来用自定义函数替换现有的 [标签插件](/zh-cn/docs/tag-plugins)。 -``` js +```js hexo.extend.tag.unregister(name); ``` **示例** -``` js +```js const tagFn = (args, content) => { - content = 'something'; + content = "something"; return content; }; // https://hexo.io/docs/tag-plugins#YouTube -hexo.extend.tag.unregister('youtube'); +hexo.extend.tag.unregister("youtube"); -hexo.extend.tag.register('youtube', tagFn); +hexo.extend.tag.register("youtube", tagFn); ``` ## 选项 @@ -52,10 +52,14 @@ hexo.extend.tag.register('youtube', tagFn); 插入 Youtube 影片。 -``` js -hexo.extend.tag.register('youtube', function(args){ +```js +hexo.extend.tag.register("youtube", function (args) { var id = args[0]; - return '<div class="video-container"><iframe width="560" height="315" src="http://www.youtube.com/embed/' + id + '" frameborder="0" allowfullscreen></iframe></div>'; + return ( + '<div class="video-container"><iframe width="560" height="315" src="http://www.youtube.com/embed/' + + id + + '" frameborder="0" allowfullscreen></iframe></div>' + ); }); ``` @@ -63,29 +67,43 @@ hexo.extend.tag.register('youtube', function(args){ 插入 pull quote。 -``` js -hexo.extend.tag.register('pullquote', function(args, content){ - var className = args.join(' '); - return '<blockquote class="pullquote' + className + '">' + content + '</blockquote>'; -}, {ends: true}); +```js +hexo.extend.tag.register( + "pullquote", + function (args, content) { + var className = args.join(" "); + return ( + '<blockquote class="pullquote' + + className + + '">' + + content + + "</blockquote>" + ); + }, + { ends: true }, +); ``` ### 异步渲染 插入文件。 -``` js -var fs = require('hexo-fs'); -var pathFn = require('path'); - -hexo.extend.tag.register('include_code', function(args){ - var filename = args[0]; - var path = pathFn.join(hexo.source_dir, filename); - - return fs.readFile(path).then(function(content){ - return '<pre><code>' + content + '</code></pre>'; - }); -}, {async: true}); +```js +var fs = require("hexo-fs"); +var pathFn = require("path"); + +hexo.extend.tag.register( + "include_code", + function (args) { + var filename = args[0]; + var path = pathFn.join(hexo.source_dir, filename); + + return fs.readFile(path).then(function (content) { + return "<pre><code>" + content + "</code></pre>"; + }); + }, + { async: true }, +); ``` ## Front-matter 和用户配置 @@ -94,7 +112,7 @@ hexo.extend.tag.register('include_code', function(args){ 1. -``` js +```js hexo.extend.tag.register('foo', function (args) { const [firstArg] = args; @@ -119,11 +137,11 @@ hexo.extend.tag.register('foo', function (args) { 2. -``` js index.js -hexo.extend.tag.register('foo', require('./lib/foo')(hexo)); +```js index.js +hexo.extend.tag.register("foo", require("./lib/foo")(hexo)); ``` -``` js lib/foo.js +```js lib/foo.js module.exports = hexo => { return function fooFn(args) { const [firstArg] = args; diff --git a/source/zh-cn/api/themes.md b/source/zh-cn/api/themes.md index fd01c59a9c..1c0b1c7cad 100644 --- a/source/zh-cn/api/themes.md +++ b/source/zh-cn/api/themes.md @@ -1,23 +1,24 @@ --- title: 主题 --- + `hexo.theme` 除了继承 [Box](box.html) 外,还具有存储模板的功能。 ## 获取模板 -``` js +```js hexo.theme.getView(path); ``` ## 设置模板 -``` js +```js hexo.theme.setView(path, data); ``` ## 移除模板 -``` js +```js hexo.theme.removeView(path); ``` @@ -25,10 +26,10 @@ hexo.theme.removeView(path); 模板本身有两个方法可供使用:`render` 和 `renderSync`。两者功能一样,只是前者为异步函数,而后者为同步函数,因此仅以 `render` 演示调用方法。 -``` js -var view = hexo.theme.getView('layout.swig'); +```js +var view = hexo.theme.getView("layout.swig"); -view.render({foo: 1, bar: 2}).then(function(result){ +view.render({ foo: 1, bar: 2 }).then(function (result) { // ... }); ``` diff --git a/source/zh-cn/docs/asset-folders.md b/source/zh-cn/docs/asset-folders.md index f9dded273f..7855988b1f 100644 --- a/source/zh-cn/docs/asset-folders.md +++ b/source/zh-cn/docs/asset-folders.md @@ -1,6 +1,7 @@ --- title: 资源文件夹 --- + ## 全局资源文件夹 资源(Asset)代表 `source` 文件夹中除了文章以外的所有文件,例如图片、CSS、JS 文件等。比方说,如果你的Hexo项目中只有少量图片,那最简单的方法就是将它们放在 `source/images` 文件夹中。然后通过类似于 `![](/images/image.jpg)` 的方法访问它们。 @@ -9,7 +10,7 @@ title: 资源文件夹 对于那些想要更有规律地提供图片和其他资源以及想要将他们的资源分布在各个文章上的人来说,Hexo也提供了更组织化的方式来管理资源。这个稍微有些复杂但是管理资源非常方便的功能可以通过将 `config.yml` 文件中的 `post_asset_folder` 选项设为 `true` 来打开。 -``` yaml _config.yml +```yaml _config.yml post_asset_folder: true ``` @@ -25,7 +26,7 @@ post_asset_folder: true {% asset_link slug [title] %} ``` -比如说:当你打开文章资源文件夹功能后,你把一个 `example.jpg` 图片放在了你的资源文件夹中,如果通过使用相对路径的常规 markdown 语法 `![](example.jpg)` ,它将 *不会* 出现在首页上。(但是它会在文章中按你期待的方式工作) +比如说:当你打开文章资源文件夹功能后,你把一个 `example.jpg` 图片放在了你的资源文件夹中,如果通过使用相对路径的常规 markdown 语法 `![](example.jpg)` ,它将 _不会_ 出现在首页上。(但是它会在文章中按你期待的方式工作) 正确的引用图片方式是使用下列的标签插件而不是 markdown : @@ -41,7 +42,7 @@ post_asset_folder: true 如需启用: -``` yml _config.yml +```yml _config.yml post_asset_folder: true marked: prependRoot: true @@ -49,4 +50,4 @@ marked: ``` 启用后,资源图片将会被自动解析为其对应文章的路径。 -例如: `image.jpg` 位置为 `/2020/01/02/foo/image.jpg` ,这表示它是 `/2020/01/02/foo/` 文章的一张资源图片, `![](image.jpg)` 将会被解析为 `<img src="/2020/01/02/foo/image.jpg">` 。 \ No newline at end of file +例如: `image.jpg` 位置为 `/2020/01/02/foo/image.jpg` ,这表示它是 `/2020/01/02/foo/` 文章的一张资源图片, `![](image.jpg)` 将会被解析为 `<img src="/2020/01/02/foo/image.jpg">` 。 diff --git a/source/zh-cn/docs/commands.md b/source/zh-cn/docs/commands.md index 41b888fe81..fb6edb86ee 100644 --- a/source/zh-cn/docs/commands.md +++ b/source/zh-cn/docs/commands.md @@ -6,7 +6,7 @@ title: 指令 ## init -``` bash +```bash $ hexo init [folder] ``` @@ -19,21 +19,21 @@ $ hexo init [folder] ## new -``` bash +```bash $ hexo new [layout] <title> ``` -新建一篇文章。如果没有设置 `layout` 的话,默认使用 [_config.yml](configuration.html) 中的 `default_layout` 参数代替。如果标题包含空格的话,请使用引号括起来。 +新建一篇文章。如果没有设置 `layout` 的话,默认使用 [\_config.yml](configuration.html) 中的 `default_layout` 参数代替。如果标题包含空格的话,请使用引号括起来。 -``` bash +```bash $ hexo new "post title with whitespace" ``` -参数 | 描述 ---- | --- -`-p`, `--path` | 自定义新文章的路径 -`-r`, `--replace` | 如果存在同名文章,将其替换 -`-s`, `--slug` | 文章的 Slug,作为新文章的文件名和发布后的 URL +| 参数 | 描述 | +| ----------------- | --------------------------------------------- | +| `-p`, `--path` | 自定义新文章的路径 | +| `-r`, `--replace` | 如果存在同名文章,将其替换 | +| `-s`, `--slug` | 文章的 Slug,作为新文章的文件名和发布后的 URL | 默认情况下,Hexo 会使用文章的标题来决定文章文件的路径。对于独立页面来说,Hexo 会创建一个以标题为名字的目录,并在目录中放置一个 `index.md` 文件。你可以使用 `--path` 参数来覆盖上述行为、自行决定文件的目录: @@ -53,19 +53,19 @@ hexo new page --path about/me ## generate -``` bash +```bash $ hexo generate ``` 生成静态文件。 -选项 | 描述 ---- | --- -`-d`, `--deploy` | 文件生成后立即部署网站 -`-w`, `--watch` | 监视文件变动 -`-b`, `--bail` | 生成过程中如果发生任何未处理的异常则抛出异常 -`-f`, `--force` | 强制重新生成文件<br>Hexo 引入了差分机制,如果 `public` 目录存在,那么 `hexo g` 只会重新生成改动的文件。<br>使用该参数的效果接近 `hexo clean && hexo generate` -`-c`, `--concurrency` | 最大同时生成文件的数量,默认无限制 +| 选项 | 描述 | +| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `-d`, `--deploy` | 文件生成后立即部署网站 | +| `-w`, `--watch` | 监视文件变动 | +| `-b`, `--bail` | 生成过程中如果发生任何未处理的异常则抛出异常 | +| `-f`, `--force` | 强制重新生成文件<br>Hexo 引入了差分机制,如果 `public` 目录存在,那么 `hexo g` 只会重新生成改动的文件。<br>使用该参数的效果接近 `hexo clean && hexo generate` | +| `-c`, `--concurrency` | 最大同时生成文件的数量,默认无限制 | 该命令可以简写为 @@ -75,7 +75,7 @@ $ hexo g ## publish -``` bash +```bash $ hexo publish [layout] <filename> ``` @@ -83,29 +83,29 @@ $ hexo publish [layout] <filename> ## server -``` bash +```bash $ hexo server ``` 启动服务器。默认情况下,访问网址为: `http://localhost:4000/`。 -选项 | 描述 ---- | --- -`-p`, `--port` | 重设端口 -`-s`, `--static` | 只使用静态文件 -`-l`, `--log` | 启动日记记录,使用覆盖记录格式 +| 选项 | 描述 | +| ---------------- | ------------------------------ | +| `-p`, `--port` | 重设端口 | +| `-s`, `--static` | 只使用静态文件 | +| `-l`, `--log` | 启动日记记录,使用覆盖记录格式 | ## deploy -``` bash +```bash $ hexo deploy ``` 部署网站。 -参数 | 描述 ---- | --- -`-g`, `--generate` | 部署之前预先生成静态文件 +| 参数 | 描述 | +| ------------------ | ------------------------ | +| `-g`, `--generate` | 部署之前预先生成静态文件 | 该命令可以简写为: @@ -115,19 +115,19 @@ $ hexo d ## render -``` bash +```bash $ hexo render <file1> [file2] ... ``` 渲染文件。 -参数 | 描述 ---- | --- -`-o`, `--output` | 设置输出路径 +| 参数 | 描述 | +| ---------------- | ------------ | +| `-o`, `--output` | 设置输出路径 | ## migrate -``` bash +```bash $ hexo migrate <type> ``` @@ -135,7 +135,7 @@ $ hexo migrate <type> ## clean -``` bash +```bash $ hexo clean ``` @@ -145,7 +145,7 @@ $ hexo clean ## list -``` bash +```bash $ hexo list <type> ``` @@ -153,7 +153,7 @@ $ hexo list <type> ## version -``` bash +```bash $ hexo version ``` @@ -171,7 +171,7 @@ $ hexo config [key] [value] ### 安全模式 -``` bash +```bash $ hexo --safe ``` @@ -179,7 +179,7 @@ $ hexo --safe ### 调试模式 -``` bash +```bash $ hexo --debug ``` @@ -187,7 +187,7 @@ $ hexo --debug ### 简洁模式 -``` bash +```bash $ hexo --silent ``` @@ -218,7 +218,7 @@ $ hexo generate --config custom.yml,custom2.json,custom3.yml ### 显示草稿 -``` bash +```bash $ hexo --draft ``` @@ -226,7 +226,7 @@ $ hexo --draft ### 自定义 CWD -``` bash +```bash $ hexo --cwd /path/to/cwd ``` diff --git a/source/zh-cn/docs/configuration.md b/source/zh-cn/docs/configuration.md index 6f5a2ee1fe..4fbeb8bb63 100644 --- a/source/zh-cn/docs/configuration.md +++ b/source/zh-cn/docs/configuration.md @@ -1,35 +1,36 @@ --- title: 配置 --- + 您可以在 `_config.yml` 或 [代替配置文件](#使用代替配置文件) 中修改大部分的配置。 {% youtube A0Enyn70jKU %} ## 网站 -参数 | 描述 ---- | --- -`title` | 网站标题 -`subtitle` | 网站副标题 -`description` | 网站描述 -`keywords` | 网站的关键词。支持多个关键词。 -`author` | 您的名字 -`language` | 网站使用的语言。对于简体中文用户来说,使用不同的主题可能需要设置成不同的值,请参考你的主题的文档自行设置,常见的有 `zh-Hans`和 `zh-CN`。 -`timezone` | 网站时区。Hexo 默认使用您电脑的时区。请参考 [时区列表](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) 进行设置,如 `America/New_York`, `Japan`, 和 `UTC` 。一般的,对于中国大陆地区可以使用 `Asia/Shanghai`。 +| 参数 | 描述 | +| ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `title` | 网站标题 | +| `subtitle` | 网站副标题 | +| `description` | 网站描述 | +| `keywords` | 网站的关键词。支持多个关键词。 | +| `author` | 您的名字 | +| `language` | 网站使用的语言。对于简体中文用户来说,使用不同的主题可能需要设置成不同的值,请参考你的主题的文档自行设置,常见的有 `zh-Hans`和 `zh-CN`。 | +| `timezone` | 网站时区。Hexo 默认使用您电脑的时区。请参考 [时区列表](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) 进行设置,如 `America/New_York`, `Japan`, 和 `UTC` 。一般的,对于中国大陆地区可以使用 `Asia/Shanghai`。 | 其中,`description` 主要用于SEO,告诉搜索引擎一个关于您站点的简单描述,通常建议在其中包含您网站的关键词。`author` 参数用于主题显示文章的作者。 ## 网址 -参数 | 描述 | 默认值 ---- | --- | --- -`url` | 网址, 必须以 `http://` 或 `https://` 开头 | -`root` | 网站根目录 | `url's pathname` -`permalink` | 文章的 [永久链接](permalinks.html) 格式 | `:year/:month/:day/:title/` -`permalink_defaults` | 永久链接中各部分的默认值 | -`pretty_urls` | 改写 [`permalink`](variables.html) 的值来美化 URL | -`pretty_urls.trailing_index` | 是否在永久链接中保留尾部的 `index.html`,设置为 `false` 时去除 | `true` -`pretty_urls.trailing_html` | 是否在永久链接中保留尾部的 `.html`, 设置为 `false` 时去除 (_对尾部的 `index.html`无效_) | `true` +| 参数 | 描述 | 默认值 | +| ---------------------------- | --------------------------------------------------------------------------------------- | --------------------------- | +| `url` | 网址, 必须以 `http://` 或 `https://` 开头 | +| `root` | 网站根目录 | `url's pathname` | +| `permalink` | 文章的 [永久链接](permalinks.html) 格式 | `:year/:month/:day/:title/` | +| `permalink_defaults` | 永久链接中各部分的默认值 | +| `pretty_urls` | 改写 [`permalink`](variables.html) 的值来美化 URL | +| `pretty_urls.trailing_index` | 是否在永久链接中保留尾部的 `index.html`,设置为 `false` 时去除 | `true` | +| `pretty_urls.trailing_html` | 是否在永久链接中保留尾部的 `.html`, 设置为 `false` 时去除 (_对尾部的 `index.html`无效_) | `true` | {% note info 网站存放在子目录 %} 如果您的网站存放在子目录中,例如 `http://example.com/blog`,则请将您的 `url` 设为 `http://example.com/blog` 并把 `root` 设为 `/blog/`。 @@ -37,7 +38,7 @@ title: 配置 例如: -``` yaml +```yaml # 比如,一个页面的永久链接是 http://example.com/foo/bar/index.html pretty_urls: trailing_index: false @@ -46,20 +47,20 @@ pretty_urls: ## 目录 -参数 | 描述 | 默认值 ---- | --- | --- -`source_dir` | 资源文件夹,这个文件夹用来存放内容。 | `source` -`public_dir` | 公共文件夹,这个文件夹用于存放生成的站点文件。 | `public` -`tag_dir` | 标签文件夹 | `tags` -`archive_dir` | 归档文件夹 | `archives` -`category_dir` | 分类文件夹 | `categories` -`code_dir` | Include code 文件夹,`source_dir` 下的子目录 | `downloads/code` -`i18n_dir` | 国际化(i18n)文件夹 | `:lang` -`skip_render` | 跳过指定文件的渲染。匹配到的文件将会被不做改动地复制到 `public` 目录中。您可使用 [glob 表达式](https://github.com/micromatch/micromatch#extended-globbing)来匹配路径。 | +| 参数 | 描述 | 默认值 | +| -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------- | +| `source_dir` | 资源文件夹,这个文件夹用来存放内容。 | `source` | +| `public_dir` | 公共文件夹,这个文件夹用于存放生成的站点文件。 | `public` | +| `tag_dir` | 标签文件夹 | `tags` | +| `archive_dir` | 归档文件夹 | `archives` | +| `category_dir` | 分类文件夹 | `categories` | +| `code_dir` | Include code 文件夹,`source_dir` 下的子目录 | `downloads/code` | +| `i18n_dir` | 国际化(i18n)文件夹 | `:lang` | +| `skip_render` | 跳过指定文件的渲染。匹配到的文件将会被不做改动地复制到 `public` 目录中。您可使用 [glob 表达式](https://github.com/micromatch/micromatch#extended-globbing)来匹配路径。 | 例如: -``` yaml +```yaml skip_render: "mypage/**/*" # 将会直接将 `source/mypage/index.html` 和 `source/mypage/code.js` 不做改动地输出到 'public' 目录 # 你也可以用这种方法来跳过对指定文章文件的渲染 @@ -73,24 +74,24 @@ skip_render: "_posts/test-post.md" ## 文章 -参数 | 描述 | 默认值 ---- | --- | --- -`new_post_name` | 新文章的文件名称 | `:title.md` -`default_layout` | 预设布局 | `post` -`auto_spacing` | 在中文和英文之间加入空格 | `false` -`titlecase` | 把标题转换为 title case | `false` -`external_link` | 在新标签中打开链接 | `true` -`external_link.enable` | 在新标签中打开链接 | `true` -`external_link.field` | 对整个网站(`site`)生效或仅对文章(`post`)生效 | `site` -`external_link.exclude` | 需要排除的域名。主域名和子域名如 `www` 需分别配置 | `[]` -`filename_case` | 把文件名称转换为 (1) 小写或 (2) 大写 | `0` -`render_drafts` | 显示草稿 | `false` -`post_asset_folder` | 启用 [资源文件夹](asset-folders.html) | `false` -`relative_link` | 把链接改为与根目录的相对位址 | `false` -`future` | 显示未来的文章 | `true` -`syntax_highlighter` | 代码块的设置, 请参考 [代码高亮](/zh-cn/docs/syntax-highlight) 进行设置 | `highlight.js` -`highlight` | 代码块的设置, 请参考 [Highlight.js](/zh-cn/docs/syntax-highlight#Highlight-js) 进行设置 | -`prismjs` | 代码块的设置, 请参考 [PrismJS](/zh-cn/docs/syntax-highlight#PrismJS) 进行设置 | +| 参数 | 描述 | 默认值 | +| ----------------------- | --------------------------------------------------------------------------------------- | -------------- | +| `new_post_name` | 新文章的文件名称 | `:title.md` | +| `default_layout` | 预设布局 | `post` | +| `auto_spacing` | 在中文和英文之间加入空格 | `false` | +| `titlecase` | 把标题转换为 title case | `false` | +| `external_link` | 在新标签中打开链接 | `true` | +| `external_link.enable` | 在新标签中打开链接 | `true` | +| `external_link.field` | 对整个网站(`site`)生效或仅对文章(`post`)生效 | `site` | +| `external_link.exclude` | 需要排除的域名。主域名和子域名如 `www` 需分别配置 | `[]` | +| `filename_case` | 把文件名称转换为 (1) 小写或 (2) 大写 | `0` | +| `render_drafts` | 显示草稿 | `false` | +| `post_asset_folder` | 启用 [资源文件夹](asset-folders.html) | `false` | +| `relative_link` | 把链接改为与根目录的相对位址 | `false` | +| `future` | 显示未来的文章 | `true` | +| `syntax_highlighter` | 代码块的设置, 请参考 [代码高亮](/zh-cn/docs/syntax-highlight) 进行设置 | `highlight.js` | +| `highlight` | 代码块的设置, 请参考 [Highlight.js](/zh-cn/docs/syntax-highlight#Highlight-js) 进行设置 | +| `prismjs` | 代码块的设置, 请参考 [PrismJS](/zh-cn/docs/syntax-highlight#PrismJS) 进行设置 | {% note info 相对地址 %} 默认情况下,Hexo 生成的超链接都是绝对地址。例如,如果您的网站域名为 `example.com`,您有一篇文章名为 `hello`,那么绝对链接可能像这样:`http://example.com/hello.html`,它是**绝对**于域名的。相对链接像这样:`/hello.html`,也就是说,无论用什么域名访问该站点,都没有关系,这在进行反向代理时可能用到。通常情况下,建议使用绝对地址。 @@ -98,21 +99,21 @@ skip_render: "_posts/test-post.md" ## 分类 & 标签 -参数 | 描述 | 默认值 ---- | --- | --- -`default_category` | 默认分类 | `uncategorized` -`category_map` | 分类别名 | -`tag_map` | 标签别名 | +| 参数 | 描述 | 默认值 | +| ------------------ | -------- | --------------- | +| `default_category` | 默认分类 | `uncategorized` | +| `category_map` | 分类别名 | +| `tag_map` | 标签别名 | ## 日期 / 时间格式 Hexo 使用 [Moment.js](http://momentjs.com/) 来解析和显示时间。 -参数 | 描述 | 默认值 ---- | --- | --- -`date_format` | 日期格式 | `YYYY-MM-DD` -`time_format` | 时间格式 | `HH:mm:ss` -`updated_option` | 当 Front Matter 中没有指定 [`updated`](/zh-cn/docs/variables#页面变量) 时 `updated` 的取值 | `mtime` +| 参数 | 描述 | 默认值 | +| ---------------- | ------------------------------------------------------------------------------------------ | ------------ | +| `date_format` | 日期格式 | `YYYY-MM-DD` | +| `time_format` | 时间格式 | `HH:mm:ss` | +| `updated_option` | 当 Front Matter 中没有指定 [`updated`](/zh-cn/docs/variables#页面变量) 时 `updated` 的取值 | `mtime` | {% note info updated_option %} `updated_option` 控制了当 Front Matter 中没有指定 `updated` 时,`updated` 如何取值: @@ -126,14 +127,14 @@ Hexo 使用 [Moment.js](http://momentjs.com/) 来解析和显示时间。 ## 分页 -参数 | 描述 | 默认值 ---- | --- | --- -`per_page` | 每页显示的文章量 (0 = 关闭分页功能) | `10` -`pagination_dir` | 分页目录 | `page` +| 参数 | 描述 | 默认值 | +| ---------------- | ----------------------------------- | ------ | +| `per_page` | 每页显示的文章量 (0 = 关闭分页功能) | `10` | +| `pagination_dir` | 分页目录 | `page` | 例如: -``` yaml +```yaml pagination_dir: 'page' # http://example.com/page/2 @@ -143,12 +144,12 @@ pagination_dir: 'awesome-page' ## 扩展 -参数 | 描述 ---- | --- -`theme` | 当前主题名称。值为`false`时禁用主题 -`theme_config` | 主题的配置文件。在这里放置的配置会覆盖主题目录下的 `_config.yml` 中的配置 -`deploy` | 部署部分的设置 -`meta_generator` | [Meta generator](https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/meta#%E5%B1%9E%E6%80%A7) 标签。 值为 `false` 时 Hexo 不会在头部插入该标签 +| 参数 | 描述 | +| ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | +| `theme` | 当前主题名称。值为`false`时禁用主题 | +| `theme_config` | 主题的配置文件。在这里放置的配置会覆盖主题目录下的 `_config.yml` 中的配置 | +| `deploy` | 部署部分的设置 | +| `meta_generator` | [Meta generator](https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/meta#%E5%B1%9E%E6%80%A7) 标签。 值为 `false` 时 Hexo 不会在头部插入该标签 | ### 包括或不包括目录和文件 @@ -156,11 +157,11 @@ pagination_dir: 'awesome-page' `include` 和 `exclude` 选项只会应用到 `source/` ,而 `ignore` 选项会应用到所有文件夹. -参数 | 描述 ---- | --- -`include` | Hexo 默认会不包括 `source/` 下的文件和文件夹(包括名称以下划线和 `.` 开头的文件和文件夹,Hexo 的 `_posts` 和 `_data` 等目录除外)。通过设置此字段将使 Hexo 处理他们并将它们复制到 `source` 目录下。 -`exclude` | Hexo 不包括 `source/` 下的这些文件和目录 -`ignore` | Hexo 会忽略整个 Hexo 项目下的这些文件夹或文件 +| 参数 | 描述 | +| --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `include` | Hexo 默认会不包括 `source/` 下的文件和文件夹(包括名称以下划线和 `.` 开头的文件和文件夹,Hexo 的 `_posts` 和 `_data` 等目录除外)。通过设置此字段将使 Hexo 处理他们并将它们复制到 `source` 目录下。 | +| `exclude` | Hexo 不包括 `source/` 下的这些文件和目录 | +| `ignore` | Hexo 会忽略整个 Hexo 项目下的这些文件夹或文件 | 例如: @@ -202,7 +203,7 @@ ignore: `include` 和 `exclude` 并不适用于 `themes/` 目录下的文件。如果需要忽略 `themes/` 目录下的部分文件或文件夹,可以使用 `ignore` 或在文件名之前添加下划线 `_`。 -* `source/_posts` 文件夹是一个例外,但该文件夹下任何名称以 `_` 开头的文件或文件夹仍会被忽略。不建议在该文件夹中使用 `include` 规则。 +- `source/_posts` 文件夹是一个例外,但该文件夹下任何名称以 `_` 开头的文件或文件夹仍会被忽略。不建议在该文件夹中使用 `include` 规则。 ### 使用代替配置文件 @@ -242,7 +243,7 @@ theme: "my-theme" theme_config: bio: "My awesome bio" foo: - bar: 'a' + bar: "a" ``` ```yml @@ -257,11 +258,11 @@ logo: "a-cool-image.png" ```json { - bio: "My awesome bio", - logo: "a-cool-image.png", - foo: { - bar: "a", - baz: "b" + "bio": "My awesome bio", + "logo": "a-cool-image.png", + "foo": { + "bar": "a", + "baz": "b" } } ``` @@ -281,7 +282,7 @@ theme: "my-theme" # _config.my-theme.yml bio: "My awesome bio" foo: - bar: 'a' + bar: "a" ``` ```yml @@ -296,11 +297,11 @@ logo: "a-cool-image.png" ```json { - bio: "My awesome bio", - logo: "a-cool-image.png", - foo: { - bar: "a", - baz: "b" + "bio": "My awesome bio", + "logo": "a-cool-image.png", + "foo": { + "bar": "a", + "baz": "b" } } ``` diff --git a/source/zh-cn/docs/contributing.md b/source/zh-cn/docs/contributing.md index 84b391b0f2..63cad406a6 100644 --- a/source/zh-cn/docs/contributing.md +++ b/source/zh-cn/docs/contributing.md @@ -25,7 +25,7 @@ title: 贡献 1. Fork [hexojs/hexo] 2. 把库(repository)复制到电脑上,并安装所依赖的插件。 -``` bash +```bash $ git clone https://github.com/<username>/hexo.git $ cd hexo $ npm install @@ -34,7 +34,7 @@ $ git submodule update --init 3. 新增一个功能分支。 -``` bash +```bash $ git checkout -b new_feature ``` @@ -52,7 +52,7 @@ $ git push origin new_feature - 不要修改 `package.json` 的版本号。 - 只有在测试通过的情况下您的合并申请才会被批准,在提交前别忘了进行测试。 -``` bash +```bash $ npm test ``` @@ -69,7 +69,7 @@ Hexo 文档开放源代码,您可以在 [hexojs/site] 找到源代码。 1. Fork [hexojs/site] 2. 把库(repository)复制到电脑上,并安装所依赖的插件。 -``` bash +```bash $ npm install hexo-cli -g # If you don't have hexo-cli installed $ git clone https://github.com/<username>/site.git $ cd site @@ -78,7 +78,7 @@ $ npm install 3. 开始编辑文件,您可以通过服务器预览变动。 -``` bash +```bash $ hexo server ``` diff --git a/source/zh-cn/docs/data-files.md b/source/zh-cn/docs/data-files.md index a5ea52f12f..ebe1f2366f 100644 --- a/source/zh-cn/docs/data-files.md +++ b/source/zh-cn/docs/data-files.md @@ -1,11 +1,12 @@ --- title: 数据文件 --- + 有时您可能需要在主题中使用某些数据,而这些数据并不在文章内,并且是需要重复使用的,那么您可以考虑使用 Hexo 3.0 新增的「数据文件」功能。此功能会加载 `source/_data` 内的 YAML 或 JSON 文件,如此一来您便能在网站中复用这些文件了。 举例来说,在 `source/_data` 文件夹中新建 `menu.yml` 文件: -``` yaml +```yaml Home: / Gallery: /gallery/ Archives: /archives/ diff --git a/source/zh-cn/docs/front-matter.md b/source/zh-cn/docs/front-matter.md index 135ca9882f..4dce38b5cb 100644 --- a/source/zh-cn/docs/front-matter.md +++ b/source/zh-cn/docs/front-matter.md @@ -6,7 +6,7 @@ title: Front-matter Front-matter 是文件最上方以 `---` 分隔的区域,用于指定个别文件的变量,举例来说: -``` yaml +```yaml --- title: Hello World date: 2013/7/13 20:46:25 @@ -15,20 +15,20 @@ date: 2013/7/13 20:46:25 以下是预先定义的参数,您可在模板中使用这些参数值并加以利用。 -参数 | 描述 | 默认值 ---- | --- | --- -`layout` | 布局 | [`config.default_layout`](/zh-cn/docs/configuration#文章) -`title` | 标题 | 文章的文件名 -`date` | 建立日期 | 文件建立日期 -`updated` | 更新日期 | 文件更新日期 -`comments` | 开启文章的评论功能 | `true` -`tags` | 标签(不适用于分页) | -`categories` | 分类(不适用于分页)| -`permalink` | 覆盖文章的永久链接,永久链接应该以 `/` 或 `.html` 结尾 | `null` -`excerpt` | 纯文本的页面摘要。使用 [该插件](/zh-cn/docs/tag-plugins#文章摘要和截断) 来格式化文本 | -`disableNunjucks` | 启用时禁用 Nunjucks 标签 `{{ }}`/`{% %}` 和 [标签插件](/zh-cn/docs/tag-plugins) 的渲染功能 | false -`lang` | 设置语言以覆盖 [自动检测](/zh-cn/docs/internationalization#路径) | 继承自 `_config.yml` -`published` | 文章是否发布 | 对于 `_posts` 下的文章为 `true`,对于 `_draft` 下的文章为 `false` +| 参数 | 描述 | 默认值 | +| ----------------- | ------------------------------------------------------------------------------------------ | ----------------------------------------------------------------- | +| `layout` | 布局 | [`config.default_layout`](/zh-cn/docs/configuration#文章) | +| `title` | 标题 | 文章的文件名 | +| `date` | 建立日期 | 文件建立日期 | +| `updated` | 更新日期 | 文件更新日期 | +| `comments` | 开启文章的评论功能 | `true` | +| `tags` | 标签(不适用于分页) | +| `categories` | 分类(不适用于分页) | +| `permalink` | 覆盖文章的永久链接,永久链接应该以 `/` 或 `.html` 结尾 | `null` | +| `excerpt` | 纯文本的页面摘要。使用 [该插件](/zh-cn/docs/tag-plugins#文章摘要和截断) 来格式化文本 | +| `disableNunjucks` | 启用时禁用 Nunjucks 标签 `{{ }}`/`{% %}` 和 [标签插件](/zh-cn/docs/tag-plugins) 的渲染功能 | false | +| `lang` | 设置语言以覆盖 [自动检测](/zh-cn/docs/internationalization#路径) | 继承自 `_config.yml` | +| `published` | 文章是否发布 | 对于 `_posts` 下的文章为 `true`,对于 `_draft` 下的文章为 `false` | ## 布局 @@ -40,12 +40,12 @@ date: 2013/7/13 20:46:25 只有文章支持分类和标签,您可以在 Front-matter 中设置。在其他系统中,分类和标签听起来很接近,但是在 Hexo 中两者有着明显的差别:分类具有顺序性和层次性,也就是说 `Foo, Bar` 不等于 `Bar, Foo`;而标签没有顺序和层次。 -``` yaml +```yaml categories: -- Diary + - Diary tags: -- PS3 -- Games + - PS3 + - Games ``` {% note warn 分类方法的分歧 %} @@ -63,9 +63,9 @@ categories: ```yaml categories: -- [Diary, PlayStation] -- [Diary, Games] -- [Life] + - [Diary, PlayStation] + - [Diary, Games] + - [Life] ``` 此时这篇文章同时包括三个分类: `PlayStation` 和 `Games` 分别都是父分类 `Diary` 的子分类,同时 `Life` 是一个没有子分类的分类。 @@ -75,7 +75,7 @@ categories: 除了 YAML 外,你也可以使用 JSON 来编写 Front-matter,只要将 `---` 代换成 `;;;` 即可。 -``` json +```json "title": "Hello World", "date": "2013/7/13 20:46:25" ;;; diff --git a/source/zh-cn/docs/generating.md b/source/zh-cn/docs/generating.md index 16354d8e1c..737683e143 100644 --- a/source/zh-cn/docs/generating.md +++ b/source/zh-cn/docs/generating.md @@ -1,9 +1,10 @@ --- title: 生成文件 --- + 使用 Hexo 生成静态文件快速而且简单。 -``` bash +```bash $ hexo generate ``` @@ -11,7 +12,7 @@ $ hexo generate Hexo 能够监视文件变动并立即重新生成静态文件,在生成时会比对文件的 SHA1 checksum,只有变动的文件才会写入。 -``` bash +```bash $ hexo generate --watch ``` @@ -19,7 +20,7 @@ $ hexo generate --watch 您可执行下列的其中一个命令,让 Hexo 在生成完毕后自动部署网站,两个命令的作用是相同的。 -``` bash +```bash $ hexo generate --deploy $ hexo deploy --generate ``` diff --git a/source/zh-cn/docs/github-pages.md b/source/zh-cn/docs/github-pages.md index a6e7707531..5065fdd86f 100755 --- a/source/zh-cn/docs/github-pages.md +++ b/source/zh-cn/docs/github-pages.md @@ -25,7 +25,7 @@ name: Pages on: push: branches: - - main # default branch + - main # default branch jobs: build: @@ -41,7 +41,7 @@ jobs: with: # Examples: 20, 18.19, >=16.20.2, lts/Iron, lts/Hydrogen, *, latest, current, node # Ref: https://github.com/actions/setup-node#supported-version-syntax - node-version: '20' + node-version: "20" - name: Cache NPM dependencies uses: actions/cache@v4 with: diff --git a/source/zh-cn/docs/gitlab-pages.md b/source/zh-cn/docs/gitlab-pages.md index 1a399c365e..9c4b985ffe 100644 --- a/source/zh-cn/docs/gitlab-pages.md +++ b/source/zh-cn/docs/gitlab-pages.md @@ -8,7 +8,7 @@ title: 将 Hexo 部署到 GitLab Pages 2. 将你的 Hexo 站点文件夹推送到 repository 中。默认情况下 `public` 目录将不会(并且不应该)被推送到 repository 中,建议你检查 `.gitignore` 文件中是否包含 `public` 一行,如果没有请加上。 3. 在你的站点文件夹中新建 `.gitlab-ci.yml` 文件: -``` yml +```yml image: node:10-alpine # use nodejs v10 LTS cache: paths: diff --git a/source/zh-cn/docs/helpers.md b/source/zh-cn/docs/helpers.md index 9ae1dda2d6..8bd98391c5 100644 --- a/source/zh-cn/docs/helpers.md +++ b/source/zh-cn/docs/helpers.md @@ -1,6 +1,7 @@ --- title: 辅助函数(Helpers) --- + 辅助函数帮助您在模版中快速插入内容。辅助函数不能在源文件中使用。 ## 网址 @@ -9,22 +10,22 @@ title: 辅助函数(Helpers) 在路径前加上根路径,从 Hexo 2.7 开始您应该使用此函数而不是 `config.root + path`。 -``` js +```js <%- url_for(path, [option]) %> ``` -参数 | 描述 | 默认值 ---- | --- | --- -`relative` | 是否输出相对链接 | `config.relative_link` 的值 +| 参数 | 描述 | 默认值 | +| ---------- | ---------------- | --------------------------- | +| `relative` | 是否输出相对链接 | `config.relative_link` 的值 | **示例:** -``` yml +```yml _config.yml root: /blog/ ``` -``` js +```js <%- url_for('/a/path') %> // /blog/a/path ``` @@ -32,12 +33,12 @@ root: /blog/ 是否输出相对链接,默认遵循配置文件中 `relative_link` 的值 例如, post/page 的相对路径值可能是 `/foo/bar/index.html` -``` yml +```yml _config.yml relative_link: true ``` -``` js +```js <%- url_for('/css/style.css') %> // ../../css/style.css /* 覆盖配置 @@ -51,13 +52,13 @@ relative_link: true 取得与 `from` 相对的 `to` 路径。 -``` js +```js <%- relative_url(from, to) %> ``` **示例:** -``` js +```js <%- relative_url('foo/bar/', 'css/style.css') %> // ../../css/style.css ``` @@ -68,22 +69,22 @@ relative_link: true 如果你不指定 `options` 参数,将会应用默认参数。否则,你可以将其设置为一个数字,这个数字将会作为 Gravatar 的大小参数。最后,如果你设置它一个对象,它将会被转换为 Gravatar 的一个查询字符串参数。 -``` js +```js <%- gravatar(email, [options]) %> ``` -参数 | 描述 | 默认值 ---- | --- | --- -`s` | 图片大小 | 80 -`d` | 默认头像 | -`f` | 强制使用默认图象 | -`r` | 头像等级限制 | +| 参数 | 描述 | 默认值 | +| ---- | ---------------- | ------ | +| `s` | 图片大小 | 80 | +| `d` | 默认头像 | +| `f` | 强制使用默认图象 | +| `r` | 头像等级限制 | 访问 [Gravatar](https://en.gravatar.com/site/implement/images/) 了解更多。 **示例:** -``` js +```js <%- gravatar('a@abc.com') %> // https://www.gravatar.com/avatar/b9b00e66c6b8a70f88c73cb6bdb06787 @@ -98,18 +99,18 @@ relative_link: true 在路径前加上根路径和域名。输出会被自动转码。 -``` js +```js <%- full_url_for(path) %> ``` **示例:** -``` yml +```yml _config.yml url: https://example.com/blog # example ``` -``` js +```js <%- full_url_for('/a/path') %> // https://example.com/blog/a/path ``` @@ -120,13 +121,13 @@ url: https://example.com/blog # example 加载 CSS 文件。`path` 可以是数组或字符串,如果 `path` 开头不是 `/` 或任何协议,则会自动加上根路径;如果后面没有加上 `.css` 扩展名的话,也会自动加上。对于自定义属性请使用对象类型。 -``` js +```js <%- css(path, ...) %> ``` **示例:** -``` js +```js <%- css('style.css') %> // <link rel="stylesheet" href="/style.css"> @@ -146,13 +147,13 @@ url: https://example.com/blog # example 加载 JavaScript 文件。`path` 可以是数组或字符串,如果 `path` 开头不是 `/` 或任何协议,则会自动加上根路径;如果后面没有加上 `.js` 扩展名的话,也会自动加上。对于自定义属性请使用对象类型。 -``` js +```js <%- js(path, ...) %> ``` **示例:** -``` js +```js <%- js('script.js') %> // <script src="/script.js"></script> @@ -172,19 +173,19 @@ url: https://example.com/blog # example 插入链接。 -``` js +```js <%- link_to(path, [text], [options]) %> ``` -参数 | 描述 | 默认值 ---- | --- | --- -`external` | 在新视窗打开链接 | false -`class` | Class 名称 | -`id` | ID | +| 参数 | 描述 | 默认值 | +| ---------- | ---------------- | ------ | +| `external` | 在新视窗打开链接 | false | +| `class` | Class 名称 | +| `id` | ID | **示例:** -``` js +```js <%- link_to('http://www.google.com') %> // <a href="http://www.google.com" title="http://www.google.com">http://www.google.com</a> @@ -199,22 +200,22 @@ url: https://example.com/blog # example 插入电子邮箱链接。 -``` js +```js <%- mail_to(path, [text], [options]) %> ``` -参数 | 描述 ---- | --- -`class` | Class 名称 -`id` | ID -`subject` | 邮件主题 -`cc` | 抄送(CC) -`bcc` | 密送(BCC) -`body` | 邮件内容 +| 参数 | 描述 | +| --------- | ----------- | +| `class` | Class 名称 | +| `id` | ID | +| `subject` | 邮件主题 | +| `cc` | 抄送(CC) | +| `bcc` | 密送(BCC) | +| `body` | 邮件内容 | **示例:** -``` js +```js <%- mail_to('a@abc.com') %> // <a href="mailto:a@abc.com" title="a@abc.com">a@abc.com</a> @@ -226,23 +227,23 @@ url: https://example.com/blog # example 插入图片。 -``` js +```js <%- image_tag(path, [options]) %> ``` -参数 | 描述 ---- | --- -`alt` | 图片的替代文字 -`class` | Class 名称 -`id` | ID -`width` | 图片宽度 -`height` | 图片高度 +| 参数 | 描述 | +| -------- | -------------- | +| `alt` | 图片的替代文字 | +| `class` | Class 名称 | +| `id` | ID | +| `width` | 图片宽度 | +| `height` | 图片高度 | ### favicon_tag 插入 favicon。 -``` js +```js <%- favicon_tag(path) %> ``` @@ -250,18 +251,18 @@ url: https://example.com/blog # example 插入 feed 链接。 -``` js +```js <%- feed_tag(path, [options]) %> ``` -参数 | 描述 | 默认值 ---- | --- | --- -`title` | Feed 标题 | `config.title` -`type` | Feed 类型 | +| 参数 | 描述 | 默认值 | +| ------- | --------- | -------------- | +| `title` | Feed 标题 | `config.title` | +| `type` | Feed 类型 | **示例:** -``` js +```js <%- feed_tag('atom.xml') %> // <link rel="alternate" href="/atom.xml" title="Hexo" type="application/atom+xml"> @@ -279,7 +280,7 @@ url: https://example.com/blog # example 检查 `path` 是否符合目前页面的网址。开启 `strict` 选项启用严格比对。 -``` js +```js <%- is_current(path, [strict]) %> ``` @@ -287,7 +288,7 @@ url: https://example.com/blog # example 检查当前页面是否为首页。 -``` js +```js <%- is_home() %> ``` @@ -295,7 +296,7 @@ url: https://example.com/blog # example 检查当前页面是否为首页的第一页。 -``` js +```js <%- is_home_first_page() %> ``` @@ -303,7 +304,7 @@ url: https://example.com/blog # example 检查当前页面是否为文章。 -``` js +```js <%- is_post() %> ``` @@ -311,7 +312,7 @@ url: https://example.com/blog # example 检查当前页面是否为独立页面。 -``` js +```js <%- is_page() %> ``` @@ -319,7 +320,7 @@ url: https://example.com/blog # example 检查当前页面是否为存档页面。 -``` js +```js <%- is_archive() %> ``` @@ -327,7 +328,7 @@ url: https://example.com/blog # example 检查当前页面是否为年度归档页面。 -``` js +```js <%- is_year() %> ``` @@ -335,7 +336,7 @@ url: https://example.com/blog # example 检查当前页面是否为月度归档页面。 -``` js +```js <%- is_month() %> ``` @@ -344,7 +345,7 @@ url: https://example.com/blog # example 检查当前页面是否为分类归档页面。 如果给定一个字符串作为参数,将会检查目前是否为指定分类。 -``` js +```js <%- is_category() %> <%- is_category('hobby') %> ``` @@ -354,7 +355,7 @@ url: https://example.com/blog # example 检查当前页面是否为标签归档页面。 如果给定一个字符串作为参数,将会检查目前是否为指定标签。 -``` js +```js <%- is_tag() %> <%- is_tag('hobby') %> ``` @@ -365,7 +366,7 @@ url: https://example.com/blog # example 清除字符串开头和结尾的空格。 -``` js +```js <%- trim(string) %> ``` @@ -373,13 +374,13 @@ url: https://example.com/blog # example 清除字符串中的 HTML 标签。 -``` js +```js <%- strip_html(string) %> ``` **示例:** -``` js +```js <%- strip_html('It\'s not <b>important</b> anymore!') %> // It's not important anymore! ``` @@ -388,13 +389,13 @@ url: https://example.com/blog # example 把字符串转换为正确的 Title case。 -``` js +```js <%- titlecase(string) %> ``` **示例:** -``` js +```js <%- titlecase('this is an apple') %> # This is an Apple ``` @@ -403,13 +404,13 @@ url: https://example.com/blog # example 使用 Markdown 解析字符串。 -``` js +```js <%- markdown(str) %> ``` **示例:** -``` js +```js <%- markdown('make me **strong**') %> // make me <strong>strong</strong> ``` @@ -418,13 +419,13 @@ url: https://example.com/blog # example 解析字符串。 -``` js +```js <%- render(str, engine, [options]) %> ``` **示例:** -``` js +```js <%- render('p(class="example") Test', 'pug'); %> // <p class="example">Test</p> ``` @@ -435,13 +436,13 @@ url: https://example.com/blog # example 使每行的字符串长度不超过 `length`。`length` 预设为 80。 -``` js +```js <%- word_wrap(str, [length]) %> ``` **示例:** -``` js +```js <%- word_wrap('Once upon a time', 8) %> // Once upon\n a time ``` @@ -450,13 +451,13 @@ url: https://example.com/blog # example 移除超过 `length` 长度的字符串。`length` 的默认值是 30。 -``` js +```js <%- truncate(text, length) %> ``` **示例:** -``` js +```js <%- truncate('Once upon a time in a world far far away', {length: 17}) %> // Once upon a ti... @@ -471,13 +472,13 @@ url: https://example.com/blog # example 在字符串中转义 HTML 实体。 -``` js +```js <%- escape_html(str) %> ``` **示例:** -``` js +```js <%- escape_html('<p>Hello "world".</p>') %> // <p>Hello "world".</p> ``` @@ -488,26 +489,26 @@ url: https://example.com/blog # example 加载其他模板文件,您可在 `locals` 设定区域变量。 -``` js +```js <%- partial(layout, [locals], [options]) %> ``` -参数 | 描述 | 默认值 ---- | --- | --- -`cache` | 缓存(使用 Fragment cache) | `false` -`only` | 限制局部变量。在模板中只能使用 `locals` 中设定的变量。 | `false` +| 参数 | 描述 | 默认值 | +| ------- | ------------------------------------------------------ | ------- | +| `cache` | 缓存(使用 Fragment cache) | `false` | +| `only` | 限制局部变量。在模板中只能使用 `locals` 中设定的变量。 | `false` | ### fragment_cache 局部缓存。它储存局部内容,下次使用时就能直接使用缓存。 -``` js +```js <%- fragment_cache(id, fn); ``` **示例:** -``` js +```js <%- fragment_cache('header', function(){ return '<header></header>'; }) %> @@ -519,13 +520,13 @@ url: https://example.com/blog # example 插入格式化的日期。`date` 可以是 UNIX 时间、ISO 字符串、Date 对象或 [Moment.js] 对象。`format` 默认为 `date_format` 配置信息。 -``` js +```js <%- date(date, [format]) %> ``` **示例:** -``` js +```js <%- date(Date.now()) %> // 2013-01-01 @@ -537,13 +538,13 @@ url: https://example.com/blog # example 插入 XML 格式的日期。`date` 可以是 UNIX 时间、ISO 字符串、Date 对象或 [Moment.js] 对象。 -``` js +```js <%- date_xml(date) %> ``` **示例:** -``` js +```js <%- date_xml(Date.now()) %> // 2013-01-01T00:00:00.000Z ``` @@ -552,13 +553,13 @@ url: https://example.com/blog # example 插入格式化的时间。`date` 可以是 UNIX 时间、ISO 字符串、Date 对象或 [Moment.js] 对象。`format` 默认为 `time_format` 配置信息。 -``` js +```js <%- time(date, [format]) %> ``` **示例:** -``` js +```js <%- time(Date.now()) %> // 13:05:12 @@ -570,13 +571,13 @@ url: https://example.com/blog # example 插入格式化的日期和时间。`date` 可以是 UNIX 时间、ISO 字符串、Date 对象或 [Moment.js] 对象。`format` 默认为 `date_format + time_format`。 -``` js +```js <%- full_date(date, [format]) %> ``` **示例:** -``` js +```js <%- full_date(new Date()) %> // Jan 1, 2013 0:00:00 @@ -594,7 +595,7 @@ url: https://example.com/blog # example **示例:** -``` js +```js <%- relative_date(new Date()) %> // a few seconds ago @@ -612,7 +613,7 @@ url: https://example.com/blog # example **示例:** -``` js +```js <%- time_tag(new Date()) %> // <time datetime="2024-01-22T06:35:31.108Z">2024-01-22</time> @@ -630,25 +631,25 @@ url: https://example.com/blog # example 插入分类列表。 -``` js +```js <%- list_categories([options]) %> ``` -参数 | 描述 | 默认值 ---- | --- | --- -`orderby` | 分类排列方式 | name -`order` | 分类排列顺序。`1`, `asc` 升序;`-1`, `desc` 降序。 | 1 -`show_count` | 显示每个分类的文章总数 | true -`style` | 分类列表的显示方式。使用 `list` 以无序列表(unordered list)方式显示。 | list -`separator` | 分类间的分隔符号。只有在 `style` 不是 `list` 时有用。 | , -`depth` | 要显示的分类层级。`0` 显示所有层级的分类;`-1` 和 `0` 很类似,但是显示不分层级;`1` 只显示第一层的分类。 | 0 -`class` | 分类列表的 class 名称。 | category -`transform` | 改变分类名称显示方法的函数 | -`suffix` | 为链接添加前缀 | None +| 参数 | 描述 | 默认值 | +| ------------ | -------------------------------------------------------------------------------------------------------- | -------- | +| `orderby` | 分类排列方式 | name | +| `order` | 分类排列顺序。`1`, `asc` 升序;`-1`, `desc` 降序。 | 1 | +| `show_count` | 显示每个分类的文章总数 | true | +| `style` | 分类列表的显示方式。使用 `list` 以无序列表(unordered list)方式显示。 | list | +| `separator` | 分类间的分隔符号。只有在 `style` 不是 `list` 时有用。 | , | +| `depth` | 要显示的分类层级。`0` 显示所有层级的分类;`-1` 和 `0` 很类似,但是显示不分层级;`1` 只显示第一层的分类。 | 0 | +| `class` | 分类列表的 class 名称。 | category | +| `transform` | 改变分类名称显示方法的函数 | +| `suffix` | 为链接添加前缀 | None | **示例:** -``` js +```js <%- list_categories(post.categories, { class: 'post-category', transform(str) { @@ -667,31 +668,31 @@ url: https://example.com/blog # example 插入标签列表。 -``` js +```js <%- list_tags([options]) %> ``` -选项 | 描述 | 预设值 ---- | --- | --- -`orderby` | 标签排列方式 | name -`order` | 标签排列顺序。`1`, `asc` 升序;`-1`, `desc` 降序。 | 1 -`show_count` | 显示每个标签的文章总数 | true -`style` | 标签列表的显示方式。使用 `list` 以无序列表(unordered list)方式显示。 | list -`separator` | 标签间的分隔符号。只有在 `style` 不是 `list` 时有用。 | , -`class` | 标签列表的类名(字符串)或自定义每个标签的类(对象,见下文)。 | tag -`transform` | 改变标签名称显示方法的函数。请查看 [list_categories](#list-categories) 中给出的例子 | -`amount` | 要显示的标签数量(0 = 无限制) | 0 -`suffix` | 为链接添加前缀 | None +| 选项 | 描述 | 预设值 | +| ------------ | ----------------------------------------------------------------------------------- | ------ | +| `orderby` | 标签排列方式 | name | +| `order` | 标签排列顺序。`1`, `asc` 升序;`-1`, `desc` 降序。 | 1 | +| `show_count` | 显示每个标签的文章总数 | true | +| `style` | 标签列表的显示方式。使用 `list` 以无序列表(unordered list)方式显示。 | list | +| `separator` | 标签间的分隔符号。只有在 `style` 不是 `list` 时有用。 | , | +| `class` | 标签列表的类名(字符串)或自定义每个标签的类(对象,见下文)。 | tag | +| `transform` | 改变标签名称显示方法的函数。请查看 [list_categories](#list-categories) 中给出的例子 | +| `amount` | 要显示的标签数量(0 = 无限制) | 0 | +| `suffix` | 为链接添加前缀 | None | 类的高级定制: -选项 | 描述 | 预设值 ---- | --- | --- -`class.ul` | `<ul>` 类名 (只适用于样式 `list`) | `tag-list` (列表样式) -`class.li` | `<li>` 类名 (只适用于样式 `list`) | `tag-list-item` (列表样式) -`class.a` | `<a>` 类名 | `tag-list-link` (列表样式) `tag-link` (普通样式) -`class.label` | `<span>` 类名,标签 label 存储在这里(仅适用于普通样式,当 `class.label` 被设置时,标签被放置在 `<span>` 中) | `tag-label` (普通样式) -`class.count` | `<span>` 类名,标签 counter 存储在这里 (仅当 `show_count` 为 `true`) | `tag-list-count` (列表样式) `tag-count` (普通样式) +| 选项 | 描述 | 预设值 | +| ------------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------ | +| `class.ul` | `<ul>` 类名 (只适用于样式 `list`) | `tag-list` (列表样式) | +| `class.li` | `<li>` 类名 (只适用于样式 `list`) | `tag-list-item` (列表样式) | +| `class.a` | `<a>` 类名 | `tag-list-link` (列表样式) `tag-link` (普通样式) | +| `class.label` | `<span>` 类名,标签 label 存储在这里(仅适用于普通样式,当 `class.label` 被设置时,标签被放置在 `<span>` 中) | `tag-label` (普通样式) | +| `class.count` | `<span>` 类名,标签 counter 存储在这里 (仅当 `show_count` 为 `true`) | `tag-list-count` (列表样式) `tag-count` (普通样式) | 示例: @@ -706,62 +707,62 @@ url: https://example.com/blog # example 插入归档列表。 -``` js +```js <%- list_archives([options]) %> ``` -参数 | 描述 | 默认值 ---- | --- | --- -`type` | 类型。此设定可为 `yearly` 或 `monthly`。 | monthly -`order` | 排列顺序。`1`, `asc` 升序;`-1`, `desc` 降序。 | 1 -`show_count` | 显示每个归档的文章总数 | true -`format` | 日期格式 | MMMM YYYY -`style` | 归档列表的显示方式。使用 `list` 以无序列表(unordered list)方式显示。 | list -`separator` | 归档间的分隔符号。只有在 `style` 不是 `list` 时有用。 | , -`class` | 归档列表的 class 名称。 | archive -`transform` | 改变归档名称显示方法的函数。请查看 [list_categories](#list-categories) 中给出的例子 | +| 参数 | 描述 | 默认值 | +| ------------ | ----------------------------------------------------------------------------------- | --------- | +| `type` | 类型。此设定可为 `yearly` 或 `monthly`。 | monthly | +| `order` | 排列顺序。`1`, `asc` 升序;`-1`, `desc` 降序。 | 1 | +| `show_count` | 显示每个归档的文章总数 | true | +| `format` | 日期格式 | MMMM YYYY | +| `style` | 归档列表的显示方式。使用 `list` 以无序列表(unordered list)方式显示。 | list | +| `separator` | 归档间的分隔符号。只有在 `style` 不是 `list` 时有用。 | , | +| `class` | 归档列表的 class 名称。 | archive | +| `transform` | 改变归档名称显示方法的函数。请查看 [list_categories](#list-categories) 中给出的例子 | ### list_posts 插入文章列表。 -``` js +```js <%- list_posts([options]) %> ``` -参数 | 描述 | 默认值 ---- | --- | --- -`orderby` | 文章排列方式 | date -`order` | 文章排列顺序。`1`, `asc` 升序;`-1`, `desc` 降序。 | -1 -`style` | 文章列表的显示方式。使用 `list` 以无序列表(unordered list)方式显示。 | list -`separator` | 文章间的分隔符号。只有在 `style` 不是 `list` 时有用。 | , -`class` | 文章列表的 class 名称。 | post -`amount` | 要显示的文章数量(0 = 无限制) | 6 -`transform` | 改变文章名称显示方法的函数。请查看 [list_categories](#list-categories) 中给出的例子 | +| 参数 | 描述 | 默认值 | +| ----------- | ----------------------------------------------------------------------------------- | ------ | +| `orderby` | 文章排列方式 | date | +| `order` | 文章排列顺序。`1`, `asc` 升序;`-1`, `desc` 降序。 | -1 | +| `style` | 文章列表的显示方式。使用 `list` 以无序列表(unordered list)方式显示。 | list | +| `separator` | 文章间的分隔符号。只有在 `style` 不是 `list` 时有用。 | , | +| `class` | 文章列表的 class 名称。 | post | +| `amount` | 要显示的文章数量(0 = 无限制) | 6 | +| `transform` | 改变文章名称显示方法的函数。请查看 [list_categories](#list-categories) 中给出的例子 | ### tagcloud 插入标签云。 -``` js +```js <%- tagcloud([tags], [options]) %> ``` -参数 | 描述 | 默认值 ---- | --- | --- -`min_font` | 最小字体尺寸 | 10 -`max_font` | 最大字体尺寸 | 20 -`unit` | 字体尺寸的单位 | px -`amount` | 标签总量 | 40 -`orderby` | 标签排列方式 | name -`order` | 标签排列顺序。`1`, `sac` 升序;`-1`, `desc` 降序 | 1 -`color` | 使用颜色 | false -`start_color` | 开始的颜色。您可使用十六进位值(`#b700ff`),rgba(`rgba(183, 0, 255, 1)`),hsla(`hsla(283, 100%, 50%, 1)`)或 [颜色关键字]。此变量仅在 `color` 参数开启时才有用。 | -`end_color` | 结束的颜色。您可使用十六进位值(`#b700ff`),rgba(`rgba(183, 0, 255, 1)`),hsla(`hsla(283, 100%, 50%, 1)`)或 [颜色关键字]。此变量仅在 `color` 参数开启时才有用。 | -`class` | 标签的 class name 前缀 -`level` | 不同 class name 的总数。此变量仅在 `class` 参数设定时才有用。 | 10 -`show_count` (+6.3.0) | 显示每个标签的文章总数 | false -`count_class` (+6.3.0) | 标签文章总数的 class | `count` +| 参数 | 描述 | 默认值 | +| ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| `min_font` | 最小字体尺寸 | 10 | +| `max_font` | 最大字体尺寸 | 20 | +| `unit` | 字体尺寸的单位 | px | +| `amount` | 标签总量 | 40 | +| `orderby` | 标签排列方式 | name | +| `order` | 标签排列顺序。`1`, `sac` 升序;`-1`, `desc` 降序 | 1 | +| `color` | 使用颜色 | false | +| `start_color` | 开始的颜色。您可使用十六进位值(`#b700ff`),rgba(`rgba(183, 0, 255, 1)`),hsla(`hsla(283, 100%, 50%, 1)`)或 [颜色关键字]。此变量仅在 `color` 参数开启时才有用。 | +| `end_color` | 结束的颜色。您可使用十六进位值(`#b700ff`),rgba(`rgba(183, 0, 255, 1)`),hsla(`hsla(283, 100%, 50%, 1)`)或 [颜色关键字]。此变量仅在 `color` 参数开启时才有用。 | +| `class` | 标签的 class name 前缀 | +| `level` | 不同 class name 的总数。此变量仅在 `class` 参数设定时才有用。 | 10 | +| `show_count` (+6.3.0) | 显示每个标签的文章总数 | false | +| `count_class` (+6.3.0) | 标签文章总数的 class | `count` | ## 其他 @@ -769,41 +770,41 @@ url: https://example.com/blog # example 插入分页链接。 -``` js +```js <%- paginator(options) %> ``` -参数 | 描述 | 默认值 ---- | --- | --- -`base` | 基础网址 | / -`format` | 网址格式 | page/%d/ -`total` | 分页总数 | 1 -`current` | 目前页数 | 0 -`prev_text` | 上一页链接的文字。仅在 `prev_next` 设定开启时才有用。 | Prev -`next_text` | 下一页链接的文字。仅在 `prev_next` 设定开启时才有用。 | Next -`space` | 空白文字 | … -`prev_next` | 显示上一页和下一页的链接 | true -`end_size` | 显示于两侧的页数 | 1 -`mid_size` | 显示于中间的页数 | 2 -`show_all` | 显示所有页数。如果开启此参数的话,`end_size` 和 `mid_size` 就没用了。 | false -`escape` | 转义 HTML 标签 | true -`page_class` | 分页链接的 class 名称 | `page-number` -`current_class` (+6.3.0) | 当前页链接的 class 名称 | `current` -`space_class` (+6.3.0) | 空白文字的 class 名称 | `space` -`prev_class` (+6.3.0) | 上一页链接的 class 名称 | `extend prev` -`next_class` (+6.3.0) | 下一页链接的 class 名称 | `extend next` -`force_prev_next` (+6.3.0) | 强制显示上一页和下一页的链接 | false +| 参数 | 描述 | 默认值 | +| -------------------------- | --------------------------------------------------------------------- | ------------- | +| `base` | 基础网址 | / | +| `format` | 网址格式 | page/%d/ | +| `total` | 分页总数 | 1 | +| `current` | 目前页数 | 0 | +| `prev_text` | 上一页链接的文字。仅在 `prev_next` 设定开启时才有用。 | Prev | +| `next_text` | 下一页链接的文字。仅在 `prev_next` 设定开启时才有用。 | Next | +| `space` | 空白文字 | … | +| `prev_next` | 显示上一页和下一页的链接 | true | +| `end_size` | 显示于两侧的页数 | 1 | +| `mid_size` | 显示于中间的页数 | 2 | +| `show_all` | 显示所有页数。如果开启此参数的话,`end_size` 和 `mid_size` 就没用了。 | false | +| `escape` | 转义 HTML 标签 | true | +| `page_class` | 分页链接的 class 名称 | `page-number` | +| `current_class` (+6.3.0) | 当前页链接的 class 名称 | `current` | +| `space_class` (+6.3.0) | 空白文字的 class 名称 | `space` | +| `prev_class` (+6.3.0) | 上一页链接的 class 名称 | `extend prev` | +| `next_class` (+6.3.0) | 下一页链接的 class 名称 | `extend next` | +| `force_prev_next` (+6.3.0) | 强制显示上一页和下一页的链接 | false | **示例:** -``` js +```js <%- paginator({ prev_text: '<', next_text: '>' }) %> ``` -``` html +```html <!-- Rendered as --> <a href="/1/"><</a> <a href="/1/">1</a> @@ -812,7 +813,7 @@ url: https://example.com/blog # example <a href="/3/">></a> ``` -``` js +```js <%- paginator({ prev_text: '<i class="fa fa-angle-left"></i>', next_text: '<i class="fa fa-angle-right"></i>', @@ -820,7 +821,7 @@ url: https://example.com/blog # example }) %> ``` -``` html +```html <!-- Rendered as --> <a href="/1/"><i class="fa fa-angle-left"></i></a> <a href="/1/">1</a> @@ -833,33 +834,33 @@ url: https://example.com/blog # example 插入 Google 搜索框。 -``` js +```js <%- search_form(options) %> ``` -参数 | 描述 | 默认值 ---- | --- | --- -`class` | 表单的 class name | search-form -`text` | 搜索提示文字 | Search -`button` | 显示搜索按钮。此参数可为布尔值(boolean)或字符串,当设定是字符串的时候,即为搜索按钮的文字。 | false +| 参数 | 描述 | 默认值 | +| -------- | --------------------------------------------------------------------------------------------- | ----------- | +| `class` | 表单的 class name | search-form | +| `text` | 搜索提示文字 | Search | +| `button` | 显示搜索按钮。此参数可为布尔值(boolean)或字符串,当设定是字符串的时候,即为搜索按钮的文字。 | false | ### number_format 格式化数字。 -``` js +```js <%- number_format(number, [options]) %> ``` -参数 | 描述 | 默认值 ---- | --- | --- -`precision` | 数字精度。此选项可为 `false` 或非负整数。 | false -`delimiter` | 千位数分隔符号 | , -`separator` | 整数和小数之间的分隔符号 | . +| 参数 | 描述 | 默认值 | +| ----------- | ----------------------------------------- | ------ | +| `precision` | 数字精度。此选项可为 `false` 或非负整数。 | false | +| `delimiter` | 千位数分隔符号 | , | +| `separator` | 整数和小数之间的分隔符号 | . | **示例:** -``` js +```js <%- number_format(12345.67, {precision: 1}) %> // 12,345.68 @@ -880,13 +881,13 @@ url: https://example.com/blog # example 插入 [generator tag](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta)。 -``` js +```js <%- meta_generator() %> ``` **示例:** -``` js +```js <%- meta_generator() %> // <meta name="generator" content="Hexo 4.0.0"> ``` @@ -895,54 +896,54 @@ url: https://example.com/blog # example 插入 open graph 资源。 -``` js +```js <%- open_graph([options]) %> ``` -参数 | 描述 | 默认值 ---- | --- | --- -`title` | 页面标题 (`og:title`) | `page.title` -`type` | 页面类型 (`og:type`) | article(post page)<br>website(non-post page) -`url` | 页面网址 (`og:url`) | `url` -`image` | 页面图片 (`og:image`) | 内容中的图片 -`author` | 文章作者 (`og:article:author`) | `config.author` -`date` | 文章发表时间 (`og:article:published_time`) | 页面发表时间 -`updated` | 文章修改时间 (`og:article:modified_time`) | 页面修改时间 -`language` | 文章语言 (`og:locale`) | `page.lang \|\| page.language \|\| config.language` -`site_name` | 网站名称 (`og:site_name`) | `config.title` -`description` | 页面描述 (`og:description`) | 内容摘要或前 200 字 -`twitter_card` | Twitter 卡片类型 (`twitter:card`) | summary -`twitter_id` | Twitter ID (`twitter:creator`) | -`twitter_site` | Twitter 网站 (`twitter:site`) | -`twitter_image` | Twitter 图片 (`twitter:image`) | -`google_plus` | Google+ 个人资料链接 | -`fb_admins` | Facebook 管理者 ID | -`fb_app_id` | Facebook 应用程序 ID | +| 参数 | 描述 | 默认值 | +| --------------- | ------------------------------------------ | --------------------------------------------------- | +| `title` | 页面标题 (`og:title`) | `page.title` | +| `type` | 页面类型 (`og:type`) | article(post page)<br>website(non-post page) | +| `url` | 页面网址 (`og:url`) | `url` | +| `image` | 页面图片 (`og:image`) | 内容中的图片 | +| `author` | 文章作者 (`og:article:author`) | `config.author` | +| `date` | 文章发表时间 (`og:article:published_time`) | 页面发表时间 | +| `updated` | 文章修改时间 (`og:article:modified_time`) | 页面修改时间 | +| `language` | 文章语言 (`og:locale`) | `page.lang \|\| page.language \|\| config.language` | +| `site_name` | 网站名称 (`og:site_name`) | `config.title` | +| `description` | 页面描述 (`og:description`) | 内容摘要或前 200 字 | +| `twitter_card` | Twitter 卡片类型 (`twitter:card`) | summary | +| `twitter_id` | Twitter ID (`twitter:creator`) | +| `twitter_site` | Twitter 网站 (`twitter:site`) | +| `twitter_image` | Twitter 图片 (`twitter:image`) | +| `google_plus` | Google+ 个人资料链接 | +| `fb_admins` | Facebook 管理者 ID | +| `fb_app_id` | Facebook 应用程序 ID | ### toc 解析内容中的标题标签 (h1~h6) 并插入目录。 -``` js +```js <%- toc(str, [options]) %> ``` -参数 | 描述 | 默认值 ---- | --- | --- -`class` | Class 名称 | `toc` -`class_item` (+6.3.0) | 目录元素的 Class 名称 | `${class}-item` -`class_link` (+6.3.0) | 目录内链接的 Class 名称 | `${class}-link` -`class_text` (+6.3.0) | 目录链接内文本的 Class 名称 | `${class}-text` -`class_child` (+6.3.0) | 目录内子列表的 Class 名称 | `${class}-child` -`class_number` (+6.3.0) | 目录序号的 Class 名称 | `${class}-number` -`class_level` | 目录层级的 Class 名称前缀 | `${class}-level` -`list_number` | 显示编号 | true -`max_depth` | 生成 TOC 的最大深度 | 6 -`min_depth` | 生成 TOC 的最小深度 | 1 +| 参数 | 描述 | 默认值 | +| ----------------------- | --------------------------- | ----------------- | +| `class` | Class 名称 | `toc` | +| `class_item` (+6.3.0) | 目录元素的 Class 名称 | `${class}-item` | +| `class_link` (+6.3.0) | 目录内链接的 Class 名称 | `${class}-link` | +| `class_text` (+6.3.0) | 目录链接内文本的 Class 名称 | `${class}-text` | +| `class_child` (+6.3.0) | 目录内子列表的 Class 名称 | `${class}-child` | +| `class_number` (+6.3.0) | 目录序号的 Class 名称 | `${class}-number` | +| `class_level` | 目录层级的 Class 名称前缀 | `${class}-level` | +| `list_number` | 显示编号 | true | +| `max_depth` | 生成 TOC 的最大深度 | 6 | +| `min_depth` | 生成 TOC 的最小深度 | 1 | **示例:** -``` js +```js <%- toc(page.content) %> ``` @@ -958,7 +959,7 @@ url: https://example.com/blog # example - https://github.com/hexojs/hexo/pull/4871 - https://github.com/hexojs/hexo-util/pull/269 - https://github.com/hexojs/hexo-renderer-markdown-it/pull/174 -{% endnote %} + {% endnote %} [颜色关键字]: http://www.w3.org/TR/css3-color/#svg-color [Moment.js]: http://momentjs.com/ diff --git a/source/zh-cn/docs/index.md b/source/zh-cn/docs/index.md index 667b8d6d99..929b472416 100644 --- a/source/zh-cn/docs/index.md +++ b/source/zh-cn/docs/index.md @@ -69,7 +69,7 @@ Node.js 为大多数平台提供了官方的 [安装程序](https://nodejs.org/z 所有必备的应用程序安装完成后,即可使用 npm 安装 Hexo。 -``` bash +```bash $ npm install -g hexo-cli ``` @@ -77,7 +77,7 @@ $ npm install -g hexo-cli 对于熟悉 npm 的进阶用户,可以仅局部安装 `hexo` 包。 -``` bash +```bash $ npm install hexo ``` @@ -86,9 +86,9 @@ $ npm install hexo 1. `npx hexo <command>` 2. Linux 用户可以将 Hexo 所在的目录下的 `node_modules` 添加到环境变量之中即可直接使用 `hexo <command>`: - ``` bash - echo 'PATH="$PATH:./node_modules/.bin"' >> ~/.profile - ``` +```bash +echo 'PATH="$PATH:./node_modules/.bin"' >> ~/.profile +``` ### Node.js 版本限制 @@ -98,15 +98,15 @@ $ npm install hexo 我们强烈建议永远安装 [最新版本](https://www.npmjs.com/package/hexo?activeTab=versions) 的 Hexo,以及 [推荐的 Node.js 版本](#安装前提)。 -Hexo 版本 | 最低版本 (Node.js 版本) | 最高版本 (Node.js 版本) ---- | --- | --- -7.0+ | 14.0.0 | latest -6.2+ | 12.13.0 | latest -6.0+ | 12.13.0 | 18.5.0 -5.0+ | 10.13.0 | 12.0.0 -4.1 - 4.2 | 8.10 | 10.0.0 -4.0 | 8.6 | 8.10.0 -3.3 - 3.9 | 6.9 | 8.0.0 -3.2 - 3.3 | 0.12 | 未知 -3.0 - 3.1 | 0.10 或 iojs | 未知 -0.0.1 - 2.8 | 0.10 | 未知 +| Hexo 版本 | 最低版本 (Node.js 版本) | 最高版本 (Node.js 版本) | +| ----------- | ----------------------- | ----------------------- | +| 7.0+ | 14.0.0 | latest | +| 6.2+ | 12.13.0 | latest | +| 6.0+ | 12.13.0 | 18.5.0 | +| 5.0+ | 10.13.0 | 12.0.0 | +| 4.1 - 4.2 | 8.10 | 10.0.0 | +| 4.0 | 8.6 | 8.10.0 | +| 3.3 - 3.9 | 6.9 | 8.0.0 | +| 3.2 - 3.3 | 0.12 | 未知 | +| 3.0 - 3.1 | 0.10 或 iojs | 未知 | +| 0.0.1 - 2.8 | 0.10 | 未知 | diff --git a/source/zh-cn/docs/internationalization.md b/source/zh-cn/docs/internationalization.md index 34450c9b88..b57a10ced6 100644 --- a/source/zh-cn/docs/internationalization.md +++ b/source/zh-cn/docs/internationalization.md @@ -1,12 +1,13 @@ --- title: 国际化(i18n) --- + 若要让您的网站以不同语言呈现,您可使用国际化(internationalization)功能。请先在 `_config.yml` 中调整 `language` 设定,这代表的是预设语言,您也可设定多个语言来调整预设语言的顺位。 -``` yaml +```yaml language: zh-tw -language: +language: - zh-tw - en ``` @@ -19,7 +20,7 @@ language: 在模板中,通过 `__` 或 `_p` 辅助函数,即可取得翻译后的字符串,前者用于一般使用;而后者用于复数字符串。例如: -``` yaml en.yml +```yaml en.yml index: title: Home add: Add @@ -29,7 +30,7 @@ index: other: %d videos ``` -``` js +```js <%= __('index.title') %> // Home @@ -41,13 +42,13 @@ index: 您可在 front-matter 中指定该页面的语言,也可在 `_config.yml` 中修改 `i18n_dir` 设定,让 Hexo 自动侦测。 -``` yaml +```yaml i18n_dir: :lang ``` `i18n_dir` 的预设值是 `:lang`,也就是说 Hexo 会捕获网址中的第一段以检测语言,举例来说: -``` plain +```plain /index.html => en /archives/index.html => en /zh-tw/index.html => zh-tw diff --git a/source/zh-cn/docs/migration.md b/source/zh-cn/docs/migration.md index 3fa83520cc..9d03a09300 100644 --- a/source/zh-cn/docs/migration.md +++ b/source/zh-cn/docs/migration.md @@ -1,17 +1,18 @@ --- title: 迁移 --- + ## RSS 首先,安装 `hexo-migrator-rss` 插件。 -``` bash +```bash $ npm install hexo-migrator-rss --save ``` 插件安装完成后,执行下列命令,从 RSS 迁移所有文章。`source` 可以是文件路径或网址。 -``` bash +```bash $ hexo migrate rss <source> ``` @@ -19,7 +20,7 @@ $ hexo migrate rss <source> 把 `_posts` 文件夹内的所有文件复制到 `source/_posts` 文件夹,并在 `_config.yml` 中修改 `new_post_name` 参数。 -``` yaml +```yaml new_post_name: :year-:month-:day-:title.md ``` @@ -27,7 +28,7 @@ new_post_name: :year-:month-:day-:title.md 把 Octopress `source/_posts` 文件夹内的所有文件转移到 Hexo 的 `source/_posts` 文件夹,并修改 `_config.yml` 中的 `new_post_name` 参数。 -``` yaml +```yaml new_post_name: :year-:month-:day-:title.md ``` @@ -35,7 +36,7 @@ new_post_name: :year-:month-:day-:title.md 首先,安装 `hexo-migrator-wordpress` 插件。 -``` bash +```bash $ npm install hexo-migrator-wordpress --save ``` @@ -43,7 +44,7 @@ $ npm install hexo-migrator-wordpress --save 插件安装完成后,执行下列命令来迁移所有文章。`source` 可以是 WordPress 导出的文件路径或网址。 -``` bash +```bash $ hexo migrate wordpress <source> ``` diff --git a/source/zh-cn/docs/one-command-deployment.md b/source/zh-cn/docs/one-command-deployment.md index b527a80140..6467c4fdac 100644 --- a/source/zh-cn/docs/one-command-deployment.md +++ b/source/zh-cn/docs/one-command-deployment.md @@ -6,25 +6,25 @@ title: 部署 Hexo 提供了快速方便的一键部署功能,让您只需一条命令就能将网站部署到服务器上。 -``` bash +```bash $ hexo deploy ``` 在开始之前,您必须先在 `_config.yml` 中修改参数,一个正确的部署配置中至少要有 `type` 参数,例如: -``` yaml +```yaml deploy: type: git ``` 您可同时使用多个 deployer,Hexo 会依照顺序执行每个 deployer。 -``` yaml +```yaml deploy: -- type: git - repo: -- type: heroku - repo: + - type: git + repo: + - type: heroku + repo: ``` 关于更多的部署插件,请参考 [插件](https://hexo.io/plugins/) 列表。 @@ -37,13 +37,13 @@ YAML依靠缩进来确定元素间的从属关系。因此,请确保每个depl 1. 安装 [hexo-deployer-git]。 -``` bash +```bash $ npm install hexo-deployer-git --save ``` 2. 修改配置。 -``` yaml +```yaml deploy: type: git repo: <repository url> #https://bitbucket.org/JohnSmith/johnsmith.bitbucket.io @@ -51,17 +51,17 @@ deploy: message: [message] ``` -参数 | 描述 | 默认 ---- | --- | --- -`repo` | 库(Repository)地址 | -`branch` | 分支名称 | `gh-pages` (GitHub)<br>`coding-pages` (Coding.net)<br>`master` (others) -`message` | 自定义提交信息 | `Site updated: {% raw %}{{ now('YYYY-MM-DD HH:mm:ss') }}{% endraw %}`) -`token` | 可选的令牌值,用于认证 repo。用 `$` 作为前缀从而从环境变量中读取令牌 +| 参数 | 描述 | 默认 | +| --------- | -------------------------------------------------------------------- | ----------------------------------------------------------------------- | +| `repo` | 库(Repository)地址 | +| `branch` | 分支名称 | `gh-pages` (GitHub)<br>`coding-pages` (Coding.net)<br>`master` (others) | +| `message` | 自定义提交信息 | `Site updated: {% raw %}{{ now('YYYY-MM-DD HH:mm:ss') }}{% endraw %}`) | +| `token` | 可选的令牌值,用于认证 repo。用 `$` 作为前缀从而从环境变量中读取令牌 | 3. 生成站点文件并推送至远程库。执行 `hexo clean && hexo deploy`。 - - 除非你使用令牌或 SSH 密钥认证,否则你会被提示提供目标仓库的用户名和密码。 - - hexo-deployer-git 并不会存储你的用户名和密码. 请使用 [git-credential-cache](https://git-scm.com/docs/git-credential-cache) 来临时存储它们。 +- 除非你使用令牌或 SSH 密钥认证,否则你会被提示提供目标仓库的用户名和密码。 +- hexo-deployer-git 并不会存储你的用户名和密码. 请使用 [git-credential-cache](https://git-scm.com/docs/git-credential-cache) 来临时存储它们。 4. 登入 Github/BitBucket/Gitlab,请在库设置(Repository Settings)中将默认分支设置为`_config.yml`配置中的分支名称。稍等片刻,您的站点就会显示在您的Github Pages中。 @@ -81,23 +81,23 @@ Hexo 在部署你的站点生成的文件时并不会更新你的站点目录。 安装 [hexo-deployer-heroku]。 -``` bash +```bash $ npm install hexo-deployer-heroku --save ``` 修改配置。 -``` yaml +```yaml deploy: type: heroku repo: <repository url> message: [message] ``` -参数 | 描述 ---- | --- -`repo` | Heroku 库(Repository)地址 -`message` | 自定提交信息 (默认为 `Site updated: {% raw %}{{ now('YYYY-MM-DD HH:mm:ss') }}{% endraw %}`) +| 参数 | 描述 | +| --------- | ------------------------------------------------------------------------------------------- | +| `repo` | Heroku 库(Repository)地址 | +| `message` | 自定提交信息 (默认为 `Site updated: {% raw %}{{ now('YYYY-MM-DD HH:mm:ss') }}{% endraw %}`) | ## Netlify @@ -113,13 +113,13 @@ deploy: 安装 [hexo-deployer-rsync]。 -``` bash +```bash $ npm install hexo-deployer-rsync --save ``` 修改配置。 -``` yaml +```yaml deploy: type: rsync host: <host> @@ -131,15 +131,15 @@ deploy: ignore_errors: [true|false] ``` -参数 | 描述 | 默认值 ---- | --- | --- -`host` | 远程主机的地址 | -`user` | 使用者名称 | -`root` | 远程主机的根目录 | -`port` | 端口 | 22 -`delete` | 删除远程主机上的旧文件 | true -`verbose` | 显示调试信息 | true -`ignore_errors` | 忽略错误 | false +| 参数 | 描述 | 默认值 | +| --------------- | ---------------------- | ------ | +| `host` | 远程主机的地址 | +| `user` | 使用者名称 | +| `root` | 远程主机的根目录 | +| `port` | 端口 | 22 | +| `delete` | 删除远程主机上的旧文件 | true | +| `verbose` | 显示调试信息 | true | +| `ignore_errors` | 忽略错误 | false | {% note info rsync部署模块的工作方式 %} 需要注意的是,要求您提供的实际上是一个能通过SSH登陆远程主机的Linux用户。Hexo会自动处理关于rsync使用的一切操作。因此,您需要在远程主机上为您的Hexo站点建立一个用户,并允许其通过SSH登陆。不过,这里的`port`,的确是指rsync监听的端口,请确保防火墙打开了该端口。 @@ -153,35 +153,35 @@ deploy: 安装 [hexo-deployer-openshift]。 -``` bash +```bash $ npm install hexo-deployer-openshift --save ``` 修改配置。 -``` yaml +```yaml deploy: type: openshift repo: <repository url> message: [message] ``` -参数 | 描述 ---- | --- -`repo` | OpenShift 库(Repository)地址 -`message` | 自定提交信息 (默认为 `Site updated: {% raw %}{{ now('YYYY-MM-DD HH:mm:ss') }}{% endraw %}`) +| 参数 | 描述 | +| --------- | ------------------------------------------------------------------------------------------- | +| `repo` | OpenShift 库(Repository)地址 | +| `message` | 自定提交信息 (默认为 `Site updated: {% raw %}{{ now('YYYY-MM-DD HH:mm:ss') }}{% endraw %}`) | ## FTPSync 安装 [hexo-deployer-ftpsync]。 -``` bash +```bash $ npm install hexo-deployer-ftpsync --save ``` 修改配置。 -``` yaml +```yaml deploy: type: ftpsync host: <host> @@ -193,15 +193,17 @@ deploy: verbose: [true|false] ``` -参数 | 描述 | 默认值 ---- | --- | --- -`host` | 远程主机的地址 | -`user` | 使用者名称 | -`pass` | 密码 | -`remote` | 远程主机的根目录 | `/` -`port` | 端口 | 21 -`clear` | 在上传前移除远程主机的根目录下所有的文件和目录 | false -`verbose` | 显示调试信息 | false +| 参数 | 描述 | 默认值 | +| ------------- | ---------------------------------------------- | ------ | +| `host` | 远程主机的地址 | +| `user` | 使用者名称 | +| `pass` | 密码 | +| `remote` | 远程主机的根目录 | `/` | +| `port` | 端口 | 21 | +| `clear` | 在上传前移除远程主机的根目录下所有的文件和目录 | false | +| `ignore` | 忽略的文件或目录 | +| `connections` | 使用的连接数 | 1 | +| `verbose` | 显示调试信息 | false | {% note warn FTP部署可能出现的问题 %} 您可能需要预先通过其他方式将所有文件上传到远程主机中。否则初次使用ftpsync插件就可能出现报错。另外,由于FTP协议的特征,它每传送一个文件就需要一次握手,相对速度较慢。 @@ -211,13 +213,13 @@ deploy: 安装 [hexo-deployer-sftp]。 -``` bash +```bash $ npm install hexo-deployer-sftp --save ``` 修改配置。 -``` yaml +```yaml deploy: type: sftp host: <host> @@ -230,16 +232,16 @@ deploy: agent: [path/to/agent/socket] ``` -参数 | 描述 | 默认值 ---- | --- | --- -`host` | 远程主机的地址 | -`user` | 使用者名称 | -`pass` | 密码 | -`remotePath` | 远程主机的根目录 | `/` -`port` | 端口 | 22 -`privateKey` | ssh私钥的目录地址 | -`passphrase` | (可省略)ssh私钥的密码短语 | -`agent` | ssh套接字的目录地址 | `$SSH_AUTH_SOCK` +| 参数 | 描述 | 默认值 | +| ------------ | --------------------------- | ---------------- | +| `host` | 远程主机的地址 | +| `user` | 使用者名称 | +| `pass` | 密码 | +| `remotePath` | 远程主机的根目录 | `/` | +| `port` | 端口 | 22 | +| `privateKey` | ssh私钥的目录地址 | +| `passphrase` | (可省略)ssh私钥的密码短语 | +| `agent` | ssh套接字的目录地址 | `$SSH_AUTH_SOCK` | ## Vercel @@ -301,8 +303,8 @@ $ hexo generate —deploy && bip deploy 2. 修改配置。 - ``` yaml - deploy: # 所有部署器的根配置块 +```yaml +deploy: # 所有部署器的根配置块 - type: rss3 endpoint: https://hub.rss3.io privateKey: 47e18d6c386898b424025cd9db446f779ef24ad33a26c499c87bb3d9372540ba @@ -312,14 +314,14 @@ $ hexo generate —deploy && bip deploy api: key: d693df715d3631e489d6 secret: ee8b74626f12b61c1a4bde3b8c331ad390567c86ba779c9b18561ee92c1cbff0 - ``` +``` -| 参数 | 描述 | -| ----------------- | ---------------------- | +| 参数 | 描述 | +| ----------------- | ----------------------- | | `endpoint` | 一个 RSS3 Hub 的链接 | | `privateKey` | 您的私钥, 64 字节 | | `ipfs/deploy` | 是否部署到 IPFS 上 | -| `ipfs/gateway` | IPFS API 网关 | +| `ipfs/gateway` | IPFS API 网关 | | `ipfs/api/key` | IPFS 网关相关的验证内容 | | `ipfs/api/secret` | IPFS 网关相关的验证内容 | diff --git a/source/zh-cn/docs/permalinks.md b/source/zh-cn/docs/permalinks.md index af8e914771..83f67eecd6 100644 --- a/source/zh-cn/docs/permalinks.md +++ b/source/zh-cn/docs/permalinks.md @@ -1,84 +1,85 @@ --- title: 永久链接(Permalinks) --- + 您可以在 `_config.yml` 配置中调整网站的永久链接或者在每篇文章的 Front-matter 中指定。 ### 变量 除了下列变量外,您还可使用除了 `:path` 和 `:permalink` 之外 Front-matter 中的所有属性。 -变量 | 描述 ---- | --- -`:year` | 文章的发表年份(4 位数) -`:month` | 文章的发表月份(2 位数) -`:i_month` | 文章的发表月份(不含前导零) -`:day` | 文章的发表日期 (2 位数) -`:i_day` | 文章的发表日期(不含前导零) -`:hour` | 文章发表时的小时 (2 位数) -`:minute` | 文章发表时的分钟 (2 位数) -`:second` | 文章发表时的秒钟 (2 位数) -`:title` | 文件名称 (相对于 "source/_posts/" 文件夹) -`:name` | 文件名称 -`:post_title` | 文章标题 -`:id` | 文章 ID (_[清除缓存](/zh-cn/docs/commands#clean)时不具有持久性_) -`:category` | 分类。如果文章没有分类,则是 `default_category` 配置信息。 -`:hash` | 文件名(与 `:title` 相同)和日期的 SHA1 哈希值(12位16进制数) +| 变量 | 描述 | +| ------------- | ---------------------------------------------------------------- | +| `:year` | 文章的发表年份(4 位数) | +| `:month` | 文章的发表月份(2 位数) | +| `:i_month` | 文章的发表月份(不含前导零) | +| `:day` | 文章的发表日期 (2 位数) | +| `:i_day` | 文章的发表日期(不含前导零) | +| `:hour` | 文章发表时的小时 (2 位数) | +| `:minute` | 文章发表时的分钟 (2 位数) | +| `:second` | 文章发表时的秒钟 (2 位数) | +| `:title` | 文件名称 (相对于 "source/\_posts/" 文件夹) | +| `:name` | 文件名称 | +| `:post_title` | 文章标题 | +| `:id` | 文章 ID (_[清除缓存](/zh-cn/docs/commands#clean)时不具有持久性_) | +| `:category` | 分类。如果文章没有分类,则是 `default_category` 配置信息。 | +| `:hash` | 文件名(与 `:title` 相同)和日期的 SHA1 哈希值(12位16进制数) | 您可在 `permalink_defaults` 参数下调整永久链接中各变量的默认值: -``` yaml +```yaml permalink_defaults: lang: en ``` ### 示例 -``` yaml source/_posts/hello-world.md +```yaml source/_posts/hello-world.md title: Hello World date: 2013-07-14 17:01:34 categories: -- foo -- bar + - foo + - bar ``` -参数 | 结果 ---- | --- -`:year/:month/:day/:title/` | 2013/07/14/hello-world/ -`:year-:month-:day-:title.html` | 2013-07-14-hello-world.html -`:category/:title/` | foo/bar/hello-world/ -`:title-:hash/` | hello-world-a2c8ac003b43/ +| 参数 | 结果 | +| ------------------------------- | --------------------------- | +| `:year/:month/:day/:title/` | 2013/07/14/hello-world/ | +| `:year-:month-:day-:title.html` | 2013-07-14-hello-world.html | +| `:category/:title/` | foo/bar/hello-world/ | +| `:title-:hash/` | hello-world-a2c8ac003b43/ | -``` yaml source/_posts/lorem/hello-world.md +```yaml source/_posts/lorem/hello-world.md title: Hello World date: 2013-07-14 17:01:34 categories: -- foo -- bar + - foo + - bar ``` -参数 | 结果 ---- | --- -`:year/:month/:day/:title/` | 2013/07/14/lorem/hello-world/ -`:year/:month/:day/:name/` | 2013/07/14/hello-world/ +| 参数 | 结果 | +| --------------------------- | ----------------------------- | +| `:year/:month/:day/:title/` | 2013/07/14/lorem/hello-world/ | +| `:year/:month/:day/:name/` | 2013/07/14/hello-world/ | ### 多语种支持 若要建立一个多语种的网站,您可修改 `new_post_name` 和 `permalink` 参数,如下: -``` yaml +```yaml new_post_name: :lang/:title.md permalink: :lang/:title/ ``` 当您建立新文章时,文章会被储存到: -``` bash +```bash $ hexo new "Hello World" --lang tw # => source/_posts/tw/Hello-World.md ``` 而网址会是: -``` plain +```plain http://localhost:4000/tw/hello-world/ ``` diff --git a/source/zh-cn/docs/plugins.md b/source/zh-cn/docs/plugins.md index 07e49cc3ac..745321ddc1 100644 --- a/source/zh-cn/docs/plugins.md +++ b/source/zh-cn/docs/plugins.md @@ -1,6 +1,7 @@ --- title: 插件 --- + Hexo 有强大的插件系统,使您能轻松扩展功能而不用修改核心模块的源码。在 Hexo 中有两种形式的插件: ### 脚本(Scripts) @@ -13,7 +14,7 @@ Hexo 有强大的插件系统,使您能轻松扩展功能而不用修改核心 文件夹内至少要包含 2 个文件:一个是主程序,另一个是 `package.json`,描述插件的用途和所依赖的插件。 -``` plain +```plain . ├── index.js └── package.json @@ -21,7 +22,7 @@ Hexo 有强大的插件系统,使您能轻松扩展功能而不用修改核心 `package.json` 中至少要包含 `name`, `version`, `main` 属性,例如: -``` json package.json +```json package.json { "name": "hexo-my-plugin", "version": "0.0.1", diff --git a/source/zh-cn/docs/server.md b/source/zh-cn/docs/server.md index 613146d313..4c3bd16de6 100644 --- a/source/zh-cn/docs/server.md +++ b/source/zh-cn/docs/server.md @@ -1,23 +1,24 @@ --- title: 服务器 --- + ## [hexo-server] Hexo 3.0 把服务器独立成了个别模块,您必须先安装 [hexo-server] 才能使用。 -``` bash +```bash $ npm install hexo-server --save ``` 安装完成后,输入以下命令以启动服务器,您的网站会在 `http://localhost:4000` 下启动。在服务器启动期间,Hexo 会监视文件变动并自动更新,您无须重启服务器。 -``` bash +```bash $ hexo server ``` 如果您想要更改端口,或是在执行时遇到了 `EADDRINUSE` 错误,可以在执行时使用 `-p` 选项指定其他端口,如下: -``` bash +```bash $ hexo server -p 5000 ``` @@ -25,7 +26,7 @@ $ hexo server -p 5000 在静态模式下,服务器只处理 `public` 文件夹内的文件,而不会处理文件变动,在执行时,您应该先自行执行 `hexo generate`,此模式通常用于生产环境(production mode)下。 -``` bash +```bash $ hexo server -s ``` @@ -33,7 +34,7 @@ $ hexo server -s 服务器默认运行在 `0.0.0.0`,您可以覆盖默认的 IP 设置,如下: -``` bash +```bash $ hexo server -i 192.168.1.1 ``` diff --git a/source/zh-cn/docs/setup.md b/source/zh-cn/docs/setup.md index f26724a08f..161855c23a 100644 --- a/source/zh-cn/docs/setup.md +++ b/source/zh-cn/docs/setup.md @@ -6,7 +6,7 @@ title: 建站 安装 Hexo 完成后,请执行下列命令,Hexo 将会在指定文件夹中新建所需要的文件。 -``` bash +```bash $ hexo init <folder> $ cd <folder> $ npm install @@ -14,7 +14,7 @@ $ npm install 新建完成后,指定文件夹的目录如下: -``` plain +```plain . ├── _config.yml ├── package.json @@ -25,7 +25,7 @@ $ npm install └── themes ``` -### _config.yml +### \_config.yml 网站的 [配置](configuration.html) 信息,您可以在此配置大部分的参数。 @@ -33,7 +33,7 @@ $ npm install 应用程序的信息。[EJS](https://ejs.co/), [Stylus](http://learnboost.github.io/stylus/) 和 [Markdown](http://daringfireball.net/projects/markdown/) 渲染引擎 已默认安装,您可以自由移除。 -``` json package.json +```json package.json { "name": "hexo-site", "version": "0.0.0", diff --git a/source/zh-cn/docs/syntax-highlight.md b/source/zh-cn/docs/syntax-highlight.md index 1fda8e2cea..157cc41df6 100644 --- a/source/zh-cn/docs/syntax-highlight.md +++ b/source/zh-cn/docs/syntax-highlight.md @@ -17,7 +17,7 @@ code snippet code snippet {% endcode %} -``` [language] [title] [url] [link text] [additional options] +```[language] [title] [url] [link text] [additional options] code snippet ``` ```` @@ -37,7 +37,7 @@ highlight: auto_detect: false line_number: true line_threshold: 0 - tab_replace: '' + tab_replace: "" exclude_languages: - example wrap: true @@ -47,7 +47,7 @@ prismjs: preprocess: true line_number: true line_threshold: 0 - tab_replace: '' + tab_replace: "" ``` v7.0.0及以上: @@ -59,7 +59,7 @@ highlight: auto_detect: false line_number: true line_threshold: 0 - tab_replace: '' + tab_replace: "" exclude_languages: - example wrap: true @@ -68,7 +68,7 @@ prismjs: preprocess: true line_number: true line_threshold: 0 - tab_replace: '' + tab_replace: "" ``` 以上为 Hexo 的默认配置。 @@ -89,7 +89,7 @@ v7.0.0及以上: ```yaml # _config.yml -syntax_highlighter: # empty +syntax_highlighter: # empty ``` 当 `highlight.enable` 和 `prismjs.enable` 均为 `false` (v7.0.0以下)或 `syntax_highlighter` 为空(v7.0.0及以上)时,代码块输出的 HTML 由相应的渲染器控制。举个例子:[`marked.js`](https://github.com/markedjs/marked)(Hexo 的默认 Markdown 渲染器 [`hexo-renderer-marked`](https://github.com/hexojs/hexo-renderer-marked) 由此驱动)会把语言加入 `<code>` 标签的 `class` 中: @@ -119,7 +119,7 @@ highlight: auto_detect: false line_number: true line_threshold: 0 - tab_replace: ' ' + tab_replace: " " exclude_languages: - example wrap: true @@ -137,7 +137,7 @@ highlight: auto_detect: false line_number: true line_threshold: 0 - tab_replace: ' ' + tab_replace: " " exclude_languages: - example wrap: true @@ -166,18 +166,18 @@ Hexo 通过用 `<figure>` 和 `<table>` 包裹其代码块为其添加了行号 ```html <figure class="highlight yaml"> -<table> -<tbody> -<tr> - <td class="gutter"> - <pre><span class="line">1</span><br></pre> - </td> - <td class="code"> - <pre><span class="line"><span class="attr">hello:</span><span class="string">hexo</span></span><br></pre> - </td> -</tr> -</tbody> -</table> + <table> + <tbody> + <tr> + <td class="gutter"> + <pre><span class="line">1</span><br></pre> + </td> + <td class="code"> + <pre><span class="line"><span class="attr">hello:</span><span class="string">hexo</span></span><br></pre> + </td> + </tr> + </tbody> + </table> </figure> ``` @@ -193,7 +193,6 @@ Hexo 通过用 `<figure>` 和 `<table>` 包裹其代码块为其添加了行号 用代码内的 tab (`\t`) 替换为给定值,默认值是两个空格。 - ### exclude_languages (+6.1.0) 如果语言符合这个选项,则输出仅仅会被 `<pre><code class="lang"></code></pre>` 包裹,并且不会在内部渲染所有的标签(`span` 和 `br`)。 @@ -239,7 +238,7 @@ prismjs: preprocess: true line_number: true line_threshold: 0 - tab_replace: '' + tab_replace: "" ``` v7.0.0及以上: @@ -251,7 +250,7 @@ prismjs: preprocess: true line_number: true line_threshold: 0 - tab_replace: '' + tab_replace: "" ``` PrismJS 默认禁用。启用 PrismJS 前应设置 `highlight.enable` 为 `false`(v7.0.0以下)或设置 `syntax_highlighter` 为 `prismjs`(v7.0.0及以上)。 diff --git a/source/zh-cn/docs/tag-plugins.md b/source/zh-cn/docs/tag-plugins.md index 8bace8c5a1..437d145dff 100644 --- a/source/zh-cn/docs/tag-plugins.md +++ b/source/zh-cn/docs/tag-plugins.md @@ -1,6 +1,7 @@ --- title: 标签插件(Tag Plugins) --- + 标签插件和 Front-matter 中的标签不同,它们是用于在文章中快速插入特定内容的插件。 虽然你可以使用任何格式书写你的文章,但是标签插件永远可用,且语法也都是一致的。 @@ -83,14 +84,14 @@ code snippet 以 `option:value` 的格式指定额外选项,例如:`line_number:false first_line:5`。 -额外选项 | 描述 | 默认值 ---- | --- | --- -`line_number` | 显示行号 | `true` -`line_threshold` | 只有代码块的行数超过该阈值,才显示行数 | `0` | -`highlight` | 启用代码高亮 | `true` -`first_line` | 指定第一个行号 | `1` -`mark` | 突出显示特定的行,每个值用逗号分隔。 使用破折号指定数字范围<br>例如: `mark:1,4-7,10` 将标记第1、4至7和10行 | -`wrap` | 用 [`<table>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table) 包裹代码块 | `true` +| 额外选项 | 描述 | 默认值 | +| ---------------- | ----------------------------------------------------------------------------------------------------------- | ------ | +| `line_number` | 显示行号 | `true` | +| `line_threshold` | 只有代码块的行数超过该阈值,才显示行数 | `0` | +| `highlight` | 启用代码高亮 | `true` | +| `first_line` | 指定第一个行号 | `1` | +| `mark` | 突出显示特定的行,每个值用逗号分隔。 使用破折号指定数字范围<br>例如: `mark:1,4-7,10` 将标记第1、4至7和10行 | +| `wrap` | 用 [`<table>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table) 包裹代码块 | `true` | ### 示例 @@ -140,7 +141,7 @@ _.compact([0, 1, false, 2, '', 3]); ``` {% codeblock _.compact http://underscorejs.org/#compact Underscore.js %} -_.compact([0, 1, false, 2, '', 3]); +\_.compact([0, 1, false, 2, '', 3]); => [1, 2, 3] {% endcodeblock %} @@ -149,9 +150,9 @@ _.compact([0, 1, false, 2, '', 3]); 另一种形式的代码块,不同的是它使用三个反引号来包裹。 {% raw %} -``` [language] [title] [url] [link text] +`` [language] [title] [url] [link text] code snippet -``` +`` {% endraw %} ## Pull Quote @@ -335,6 +336,7 @@ content ``` {% post_link hexo-4-released 'How to use <b> tag in title' %} ``` + {% post_link hexo-4-released 'How to use <b> tag in title' %} **禁止对标题的特殊字符进行转义** @@ -342,6 +344,7 @@ content ``` {% post_link hexo-4-released '<b>bold</b> custom title' false %} ``` + {% post_link hexo-4-released '<b>bold</b> custom title' false %} ## 引用资源 @@ -364,32 +367,32 @@ _hexo-renderer-marked 3.1.0+ 可以(可选)自动解析图片的文章路径 `{% asset_img foo.jpg %}` -``` html -<img src="/2020/01/02/hello/foo.jpg"> +```html +<img src="/2020/01/02/hello/foo.jpg" /> ``` **自定义 class 属性** `{% asset_img post-image foo.jpg %}` -``` html -<img src="/2020/01/02/hello/foo.jpg" class="post-image"> +```html +<img src="/2020/01/02/hello/foo.jpg" class="post-image" /> ``` **展示尺寸** `{% asset_img foo.jpg 500 400 %}` -``` html -<img src="/2020/01/02/hello/foo.jpg" width="500" height="400"> +```html +<img src="/2020/01/02/hello/foo.jpg" width="500" height="400" /> ``` **title 和 alt 属性** `{% asset_img logo.svg "lorem ipsum'dolor'" %}` -``` html -<img src="/2020/01/02/hello/foo.jpg" title="lorem ipsum" alt="dolor"> +```html +<img src="/2020/01/02/hello/foo.jpg" title="lorem ipsum" alt="dolor" /> ``` ## URL @@ -404,23 +407,23 @@ _hexo-renderer-marked 3.1.0+ 可以(可选)自动解析图片的文章路径 **示例:** -``` yml +```yml _config.yml root: /blog/ # example ``` -``` +``` {% url_for blog index.html %} ``` -``` html +```html <a href="/blog/index.html">blog</a> ``` 是否输出相对链接,默认遵循配置文件中 `relative_link` 的值 例如, post/page 的路径值可能是 `/foo/bar/index.html` -``` yml +```yml _config.yml relative_link: true ``` @@ -429,7 +432,7 @@ relative_link: true {% url_for blog index.html %} ``` -``` html +```html <a href="../../index.html">blog</a> ``` @@ -439,7 +442,7 @@ relative_link: true {% url_for blog index.html false %} ``` -``` html +```html <a href="/index.html">blog</a> ``` @@ -453,7 +456,7 @@ relative_link: true **示例:** -``` yml +```yml _config.yml url: https://example.com/blog # example ``` @@ -462,7 +465,7 @@ url: https://example.com/blog # example {% full_url_for index /a/path %} ``` -``` html +```html <a href="https://example.com/blog/a/path">index</a> ``` diff --git a/source/zh-cn/docs/templates.md b/source/zh-cn/docs/templates.md index e68f930003..9159f71405 100644 --- a/source/zh-cn/docs/templates.md +++ b/source/zh-cn/docs/templates.md @@ -1,38 +1,43 @@ --- title: 模版 --- + 模板决定了网站内容的呈现方式,每个主题至少都应包含一个 `index` 模板,以下是各页面相对应的模板名称: -模板 | 用途 | 回退 ---- | --- | --- -`index` | 首页 | -`post` | 文章 | `index` -`page` | 分页 | `index` -`archive` | 归档 | `index` -`category` | 分类归档 | `archive` -`tag` | 标签归档 | `archive` +| 模板 | 用途 | 回退 | +| ---------- | -------- | --------- | +| `index` | 首页 | +| `post` | 文章 | `index` | +| `page` | 分页 | `index` | +| `archive` | 归档 | `index` | +| `category` | 分类归档 | `archive` | +| `tag` | 标签归档 | `archive` | ## 布局(Layout) 如果页面结构类似,例如两个模板都有页首(Header)和页脚(Footer),您可考虑通过「布局」让两个模板共享相同的结构。一个布局文件必须要能显示 `body` 变量的内容,如此一来模板的内容才会被显示,举例来说: -``` html index.ejs +```html index.ejs index ``` -``` html layout.ejs -<!DOCTYPE html> +```html layout.ejs +<!doctype html> <html> - <body><%- body %></body> + <body> + <%- body %> + </body> </html> ``` 生成: -``` html -<!DOCTYPE html> +```html +<!doctype html> <html> - <body>index</body> + <body> + index + </body> </html> ``` @@ -42,18 +47,18 @@ index 局部模板让您在不同模板之间共享相同的组件,例如页首(Header)、页脚(Footer)或侧边栏(Sidebar)等,可利用局部模板功能分割为个别文件,让维护更加便利。举例来说: -``` html partial/header.ejs +```html partial/header.ejs <h1 id="logo"><%= config.title %></h1> ``` -``` html index.ejs +```html index.ejs <%- partial('partial/header') %> <div id="content">Home page</div> ``` 生成: -``` html +```html <h1 id="logo">My Site</h1> <div id="content">Home page</div> ``` @@ -62,18 +67,18 @@ index 您可以在局部模板中指定局部变量并使用。 -``` html partial/header.ejs +```html partial/header.ejs <h1 id="logo"><%= title %></h1> ``` -``` html index.ejs +```html index.ejs <%- partial('partial/header', {title: 'Hello World'}) %> <div id="content">Home page</div> ``` 生成: -``` html +```html <h1 id="logo">Hello World</h1> <div id="content">Home page</div> ``` @@ -86,7 +91,7 @@ index 它可用于页首、页脚、侧边栏等文件不常变动的位置,举例来说: -``` js +```js <%- fragment_cache('header', function(){ return '<header></header>'; }); @@ -94,7 +99,7 @@ index 如果您使用局部模板的话,可以更简单: -``` js +```js <%- partial('header', {}, {cache: true}); ``` diff --git a/source/zh-cn/docs/themes.md b/source/zh-cn/docs/themes.md index a6f6e2a99b..1ea231b9e0 100644 --- a/source/zh-cn/docs/themes.md +++ b/source/zh-cn/docs/themes.md @@ -1,9 +1,10 @@ --- title: 主题 --- + 创建 Hexo 主题非常容易,您只要在 `themes` 文件夹内,新增一个任意名称的文件夹,并修改 `_config.yml` 内的 `theme` 设定,即可切换主题。一个主题可能会有以下的结构: -``` plain +```plain . ├── _config.yml ├── languages @@ -12,7 +13,7 @@ title: 主题 └── source ``` -### _config.yml +### \_config.yml 主题的配置文件。和 Hexo 配置文件不同,主题配置文件修改时会自动更新,无需重启 Hexo Server。 @@ -24,7 +25,7 @@ title: 主题 布局文件夹。用于存放主题的模板文件,决定了网站内容的呈现方式,Hexo 内建 [Nunjucks] 模板引擎,您可以另外安装插件来获得 [EJS] 或 [Pug] 支持,Hexo 根据模板文件的扩展名来决定所使用的模板引擎,例如: -``` plain +```plain layout.ejs - 使用 EJS layout.swig - 使用 Swig ``` @@ -48,11 +49,11 @@ layout.swig - 使用 Swig 1. Fork [hexojs/site] 2. 把库(repository)复制到电脑上,并安装所依赖的插件。 - ```shell - $ git clone https://github.com/<username>/site.git - $ cd site - $ npm install - ``` + ```shell + $ git clone https://github.com/<username>/site.git + $ cd site + $ npm install + ``` 3. 在 `source/_data/themes/` 中创建一个新的 yaml 文件,使用您的主题名称作为文件名。 diff --git a/source/zh-cn/docs/troubleshooting.md b/source/zh-cn/docs/troubleshooting.md index 7549f647e7..360909e7b6 100644 --- a/source/zh-cn/docs/troubleshooting.md +++ b/source/zh-cn/docs/troubleshooting.md @@ -1,18 +1,19 @@ --- title: 问题解答 --- + 在使用 Hexo 时,您可能会遇到一些问题,下列的常见问题解答可能会对您有所帮助。如果您在这里找不到解答,可以在 [GitHub](https://github.com/hexojs/hexo/issues) 或 [Google Group](https://groups.google.com/group/hexo) 上提问。 ## YAML 解析错误 -``` plain +```plain JS-YAML: incomplete explicit mapping pair; a key node is missed at line 18, column 29: last_updated: Last updated: %s ``` 如果 YAML 字符串中包含冒号(`:`)的话,请加上引号。 -``` plain +```plain JS-YAML: bad indentation of a mapping entry at line 18, column 31: last_updated:"Last updated: %s" ``` @@ -23,13 +24,13 @@ JS-YAML: bad indentation of a mapping entry at line 18, column 31: ## EMFILE 错误 -``` plain +```plain Error: EMFILE, too many open files ``` 虽然 Node.js 有非阻塞 I/O,同步 I/O 的数量仍被系统所限制,在生成大量静态文件的时候,您可能会碰到 EMFILE 错误,您可以尝试提高同步 I/O 的限制数量来解决此问题。 -``` bash +```bash $ ulimit -n 10000 ``` @@ -39,7 +40,7 @@ $ ulimit -n 10000 如果遇到以下错误: -``` bash +```bash $ ulimit -n 10000 ulimit: open files: cannot modify limit: Operation not permitted ``` @@ -50,23 +51,23 @@ ulimit: open files: cannot modify limit: Operation not permitted 1. 在 `/etc/security/limits.conf` 中增加以下一行: - ``` - * - nofile 10000 +``` +* - nofile 10000 - # '*' applies to all users and '-' set both soft and hard limits - ``` +# '*' applies to all users and '-' set both soft and hard limits +``` - * 上述设置在某些情况下可能不适用,请确保 `/etc/pam.d/login` 和 `/etc/pam.d/lightdm` 有以下一行(如果这些文件不存在,请忽略此步骤): +- 上述设置在某些情况下可能不适用,请确保 `/etc/pam.d/login` 和 `/etc/pam.d/lightdm` 有以下一行(如果这些文件不存在,请忽略此步骤): - ``` - session required pam_limits.so - ``` +``` +session required pam_limits.so +``` 2. 如果你使用的是 [基于systemd](https://en.wikipedia.org/wiki/Systemd#Adoption) 的发行版,systemd 可能会覆盖 `limits.conf`。如果想要在 systemd 中设置限制,请在 `/etc/systemd/system.conf` 和 `/etc/systemd/user.conf` 中添加以下一行: - ``` - DefaultLimitNOFILE=10000 - ``` +``` +DefaultLimitNOFILE=10000 +``` 3. 重启 @@ -74,7 +75,7 @@ ulimit: open files: cannot modify limit: Operation not permitted ### RPC failed -``` plain +```plain error: RPC failed; result=22, HTTP code = 403 fatal: 'username.github.io' does not appear to be a git repository @@ -88,19 +89,19 @@ fatal: 'username.github.io' does not appear to be a git repository ## 服务器问题 -``` plain +```plain Error: listen EADDRINUSE ``` 您可能同时开启两个 Hexo 服务器,或者有其他应用程序正在占用相同的端口,请尝试修改 `port` 参数,或是在启动 Hexo 服务器时加上 `-p` 选项。 -``` bash +```bash $ hexo server -p 5000 ``` ## 插件安装问题 -``` plain +```plain npm ERR! node-waf configure build ``` @@ -135,7 +136,7 @@ Hexo 使用 [Warehouse] 存储数据,它不是一般数组所以必须先进 有时数据可能没有被更新,或是生成的文件与修改前的相同,您可以尝试清除缓存并再执行一次。 -``` bash +```bash $ hexo clean ``` @@ -153,7 +154,7 @@ $ hexo clean ## 转义(Escape)内容 -Hexo 使用 [Nunjucks] 来解析文章(旧版本使用 [Swig],两者语法类似),内容若包含 `{{ }}` 或 `{% %}` 可能导致解析错误,您可以用 [`raw`](/zh-cn/docs/tag-plugins#Raw) 标签包裹,单反引号 ```` `{{ }}` ```` 或 三反引号 来避免潜在问题发生。 +Hexo 使用 [Nunjucks] 来解析文章(旧版本使用 [Swig],两者语法类似),内容若包含 `{{ }}` 或 `{% %}` 可能导致解析错误,您可以用 [`raw`](/zh-cn/docs/tag-plugins#Raw) 标签包裹,单反引号 `` `{{ }}` `` 或 三反引号 来避免潜在问题发生。 此外,Nunjucks 标签也可以通过渲染器的选项(如果支持的话)、[API](/zh-cn/api/renderer#禁用-Nunjucks-标签) 或 [front-matter](/zh-cn/docs/front-matter) 来禁用。 ``` diff --git a/source/zh-cn/docs/variables.md b/source/zh-cn/docs/variables.md index a125bf7960..7c16e324ca 100644 --- a/source/zh-cn/docs/variables.md +++ b/source/zh-cn/docs/variables.md @@ -1,17 +1,18 @@ --- title: 变量 --- + ### 全局变量 -变量 | 描述 | 类型 ---- | --- | --- -`site` | [网站变量](#网站变量) | `object`; 见 [网站变量](#网站变量) -`page` | 针对该页面的内容以及 front-matter 中自定义的变量。 | `object`; 见 [页面变量](#页面变量) -`config` | 网站配置 | `object` (站点的配置文件) -`theme` | 主题配置。继承自网站配置。 | `object` (主题配置文件) -`path` | 当前页面的路径(不含根路径)| `string` -`url` | 当前页面的完整网址 | `string` -`env` | 环境变量 | `object` +| 变量 | 描述 | 类型 | +| -------- | -------------------------------------------------- | ---------------------------------- | +| `site` | [网站变量](#网站变量) | `object`; 见 [网站变量](#网站变量) | +| `page` | 针对该页面的内容以及 front-matter 中自定义的变量。 | `object`; 见 [页面变量](#页面变量) | +| `config` | 网站配置 | `object` (站点的配置文件) | +| `theme` | 主题配置。继承自网站配置。 | `object` (主题配置文件) | +| `path` | 当前页面的路径(不含根路径) | `string` | +| `url` | 当前页面的完整网址 | `string` | +| `env` | 环境变量 | `object` | {% note warn %} 从 Hexo 5.0.0 开始,Lodash 已从全局变量中移除。迁移时 [You-Dont-Need-Lodash-Underscore](https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore) 或许能为你提供帮助。 @@ -19,78 +20,78 @@ title: 变量 ### 网站变量 -变量 | 描述 | 类型 ---- | --- | --- -`site.posts` | 所有文章 | `array`,包含了站点全部的文章 `object` -`site.pages` | 所有分页 | `array`,包含了站点全部的分页 `object` -`site.categories` | 所有分类 | `array`,包含了站点全部的分类 `object` -`site.tags` | 所有标签 | `array`,包含了站点全部的标签 `object` +| 变量 | 描述 | 类型 | +| ----------------- | -------- | -------------------------------------- | +| `site.posts` | 所有文章 | `array`,包含了站点全部的文章 `object` | +| `site.pages` | 所有分页 | `array`,包含了站点全部的分页 `object` | +| `site.categories` | 所有分类 | `array`,包含了站点全部的分类 `object` | +| `site.tags` | 所有标签 | `array`,包含了站点全部的标签 `object` | ### 页面变量 **页面(`page`)** -变量 | 描述 | 类型 ---- | --- | --- -`page.title` | 页面标题 | `string` -`page.date` | 页面建立日期 | [Moment.js] 对象 -`page.updated` | 页面更新日期 | [Moment.js] 对象 -`page.comments` | 留言是否开启 | `boolean` -`page.layout` | 布局名称 | `string` -`page.content` | 页面的完整内容 | `string` -`page.excerpt` | 页面摘要 | `string` -`page.more` | 除了页面摘要的其余内容 | `string` -`page.source` | 页面原始路径 | `string` -`page.full_source` | 页面的完整原始路径 | `string` -`page.path` | 页面网址(不含根路径)。我们通常在主题中使用 `url_for(page.path)`。| `string` -`page.permalink` | 页面的完整网址 | `string` -`page.prev` | 上一个页面。如果此为第一个页面则为 `null`。| `object` 或 `null` -`page.next` | 下一个页面。如果此为最后一个页面则为 `null`。| `object` 或 `null` -`page.raw` | 文章的原始内容 | `string` -`page.photos` | 文章的照片(用于相簿)| `array` -`page.link` | 文章的外部链接(用于链接文章)| `string` +| 变量 | 描述 | 类型 | +| ------------------ | ------------------------------------------------------------------- | ------------------ | +| `page.title` | 页面标题 | `string` | +| `page.date` | 页面建立日期 | [Moment.js] 对象 | +| `page.updated` | 页面更新日期 | [Moment.js] 对象 | +| `page.comments` | 留言是否开启 | `boolean` | +| `page.layout` | 布局名称 | `string` | +| `page.content` | 页面的完整内容 | `string` | +| `page.excerpt` | 页面摘要 | `string` | +| `page.more` | 除了页面摘要的其余内容 | `string` | +| `page.source` | 页面原始路径 | `string` | +| `page.full_source` | 页面的完整原始路径 | `string` | +| `page.path` | 页面网址(不含根路径)。我们通常在主题中使用 `url_for(page.path)`。 | `string` | +| `page.permalink` | 页面的完整网址 | `string` | +| `page.prev` | 上一个页面。如果此为第一个页面则为 `null`。 | `object` 或 `null` | +| `page.next` | 下一个页面。如果此为最后一个页面则为 `null`。 | `object` 或 `null` | +| `page.raw` | 文章的原始内容 | `string` | +| `page.photos` | 文章的照片(用于相簿) | `array` | +| `page.link` | 文章的外部链接(用于链接文章) | `string` | **文章 (`post`):** 与 `page` 布局相同,但新增以下变量。 -变量 | 描述 | 类型 ---- | --- | --- -`page.published` | 如果该文章已发布则为 true | `boolean` -`page.categories` | 该文章的所有分类 | `array` -`page.tags` | 该文章的所有标签 | `array` +| 变量 | 描述 | 类型 | +| ----------------- | ------------------------- | --------- | +| `page.published` | 如果该文章已发布则为 true | `boolean` | +| `page.categories` | 该文章的所有分类 | `array` | +| `page.tags` | 该文章的所有标签 | `array` | **首页(`index`)** -变量 | 描述 | 类型 ---- | --- | --- -`page.per_page` | 每页显示的文章数量 | `number` -`page.total` | 总页数 | `number` -`page.current` | 目前页数 | `number` -`page.current_url` | 目前分页的网址 | `string` -`page.posts` | 本页文章 ([Data Model](https://hexojs.github.io/warehouse/)) | `object` -`page.prev` | 上一页的页数。如果此页是第一页的话则为 `0`。 | `number` -`page.prev_link` | 上一页的网址。如果此页是第一页的话则为 `''`。 | `string` -`page.next` | 下一页的页数。如果此页是最后一页的话则为 `0`。 | `number` -`page.next_link` | 下一页的网址。如果此页是最后一页的话则为 `''`。 | `string` -`page.path` | 当前页面的路径(不含根目录)。我们通常在主题中使用 `url_for(page.path)`。| `string` +| 变量 | 描述 | 类型 | +| ------------------ | ------------------------------------------------------------------------- | -------- | +| `page.per_page` | 每页显示的文章数量 | `number` | +| `page.total` | 总页数 | `number` | +| `page.current` | 目前页数 | `number` | +| `page.current_url` | 目前分页的网址 | `string` | +| `page.posts` | 本页文章 ([Data Model](https://hexojs.github.io/warehouse/)) | `object` | +| `page.prev` | 上一页的页数。如果此页是第一页的话则为 `0`。 | `number` | +| `page.prev_link` | 上一页的网址。如果此页是第一页的话则为 `''`。 | `string` | +| `page.next` | 下一页的页数。如果此页是最后一页的话则为 `0`。 | `number` | +| `page.next_link` | 下一页的网址。如果此页是最后一页的话则为 `''`。 | `string` | +| `page.path` | 当前页面的路径(不含根目录)。我们通常在主题中使用 `url_for(page.path)`。 | `string` | **归档 (`archive`)** :与 `index` 布局相同,但新增以下变量。 -变量 | 描述 | 类型 ---- | --- | --- -`page.archive` | 等于 `true` | `boolean` -`page.year` | 年份归档 (4位) | `number` -`page.month` | 月份归档 (没有前导零的2位数) | `number` +| 变量 | 描述 | 类型 | +| -------------- | ---------------------------- | --------- | +| `page.archive` | 等于 `true` | `boolean` | +| `page.year` | 年份归档 (4位) | `number` | +| `page.month` | 月份归档 (没有前导零的2位数) | `number` | **分类 (`category`)** :与 `index` 布局相同,但新增以下变量。 -变量 | 描述 | 类型 ---- | --- | --- -`page.category` | 分类名称 | `string` +| 变量 | 描述 | 类型 | +| --------------- | -------- | -------- | +| `page.category` | 分类名称 | `string` | **标签 (`tag`)** :与 `index` 布局相同,但新增以下变量。 -变量 | 描述 | 类型 ---- | --- | --- -`page.tag` | 标签名称 | `string` +| 变量 | 描述 | 类型 | +| ---------- | -------- | -------- | +| `page.tag` | 标签名称 | `string` | [Moment.js]: http://momentjs.com/ diff --git a/source/zh-cn/docs/writing.md b/source/zh-cn/docs/writing.md index e20988e13e..85e31152fa 100644 --- a/source/zh-cn/docs/writing.md +++ b/source/zh-cn/docs/writing.md @@ -6,7 +6,7 @@ title: 写作 你可以执行下列命令来创建一篇新文章或者新的页面。 -``` bash +```bash $ hexo new [layout] <title> ``` @@ -16,11 +16,11 @@ $ hexo new [layout] <title> Hexo 有三种默认布局:`post`、`page` 和 `draft`。在创建这三种不同类型的文件时,它们将会被保存到不同的路径;而您自定义的其他布局和 `post` 相同,都将储存到 `source/_posts` 文件夹。 -布局 | 路径 ---- | --- -`post` | `source/_posts` -`page` | `source` -`draft` | `source/_drafts` +| 布局 | 路径 | +| ------- | ---------------- | +| `post` | `source/_posts` | +| `page` | `source` | +| `draft` | `source/_drafts` | {% note tip 禁用布局 %} 如果你不希望一篇文章(post/page)使用主题处理,请在它的 front-matter 中设置 `layout: false`。详情请参考[本节](/zh-cn/docs/front-matter#布局)。 @@ -30,20 +30,20 @@ Hexo 有三种默认布局:`post`、`page` 和 `draft`。在创建这三种不 Hexo 默认以标题做为文件名称,但您可编辑 `new_post_name` 参数来改变默认的文件名称,举例来说,设为 `:year-:month-:day-:title.md` 可让您更方便的通过日期来管理文章。你可以使用以下占位符: -变量 | 描述 ---- | --- -`:title` | 标题(小写,空格将会被替换为短杠) -`:year` | 建立的年份,比如, `2015` -`:month` | 建立的月份(有前导零),比如, `04` -`:i_month` | 建立的月份(无前导零),比如, `4` -`:day` | 建立的日期(有前导零),比如, `07` -`:i_day` | 建立的日期(无前导零),比如, `7` +| 变量 | 描述 | +| ---------- | ----------------------------------- | +| `:title` | 标题(小写,空格将会被替换为短杠) | +| `:year` | 建立的年份,比如, `2015` | +| `:month` | 建立的月份(有前导零),比如, `04` | +| `:i_month` | 建立的月份(无前导零),比如, `4` | +| `:day` | 建立的日期(有前导零),比如, `07` | +| `:i_day` | 建立的日期(无前导零),比如, `7` | ### 草稿 刚刚提到了 Hexo 的一种特殊布局:`draft`,这种布局在建立时会被保存到 `source/_drafts` 文件夹,您可通过 `publish` 命令将草稿移动到 `source/_posts` 文件夹,该命令的使用方式与 `new` 十分类似,您也可在命令中指定 `layout` 来指定布局。 -``` bash +```bash $ hexo publish [layout] <title> ``` @@ -53,17 +53,17 @@ $ hexo publish [layout] <title> 在新建文章时,Hexo 会根据 `scaffolds` 文件夹内相对应的文件来建立文件,例如: -``` bash +```bash $ hexo new photo "My Gallery" ``` 在执行这行指令时,Hexo 会尝试在 `scaffolds` 文件夹中寻找 `photo.md`,并根据其内容建立文章,以下是您可以在模版中使用的变量: -变量 | 描述 ---- | --- -`layout` | 布局 -`title` | 标题 -`date` | 文件建立日期 +| 变量 | 描述 | +| -------- | ------------ | +| `layout` | 布局 | +| `title` | 标题 | +| `date` | 文件建立日期 | ### 支持的格式 diff --git a/source/zh-tw/api/box.md b/source/zh-tw/api/box.md index fbd599364c..8291f1133f 100644 --- a/source/zh-tw/api/box.md +++ b/source/zh-tw/api/box.md @@ -1,18 +1,19 @@ --- title: 箱子(Box) --- + 「箱子」是 Hexo 用來處理特定資料夾中的檔案的容器,在 Hexo 中有兩個箱子,分別是 `hexo.source` 和 `hexo.theme`,前者用於處理 `source` 資料夾,而後者用於處理主題資料夾。 ## 載入檔案 箱子提供了兩種方法來載入檔案:`process`, `watch`,前者用於載入資料夾內的所有檔案;而後者除了執行 `process` 以外,還會繼續監看檔案變動。 -``` js -box.process().then(function(){ +```js +box.process().then(function () { // ... }); -box.watch().then(function(){ +box.watch().then(function () { // 之後可呼叫 box.unwatch() 停止檔案監看 }); ``` @@ -21,7 +22,7 @@ box.watch().then(function(){ 箱子提供了多種路徑比對的模式,您可使用正規表達式(regular expression)、函數、或是一種類似於 Express 的路徑字串,例如: -``` plain +```plain posts/:id => posts/89 posts/*path => posts/2015/title ``` @@ -32,30 +33,30 @@ posts/*path => posts/2015/title 處理器(Processor)是箱子中非常重要的元素,它用於處理檔案,您可使用上述的路徑比對來限制該處理器所要處理的檔案類型。使用 `addProcessor` 來註冊處理器。 -``` js -box.addProcessor('posts/:id', function(file){ +```js +box.addProcessor("posts/:id", function (file) { // }); ``` 箱子在處理時會把目前處理的檔案內容(`file`)傳給處理器,您可透過此參數取得該檔案的資訊。 -屬性 | 描述 ---- | --- -`source` | 檔案完整路徑 -`path` | 檔案相對於箱子的路徑 -`type` | 檔案類型。有 `create`, `update`, `skip`, `delete`。 -`params` | 從路徑比對中取得的資訊 +| 屬性 | 描述 | +| -------- | --------------------------------------------------- | +| `source` | 檔案完整路徑 | +| `path` | 檔案相對於箱子的路徑 | +| `type` | 檔案類型。有 `create`, `update`, `skip`, `delete`。 | +| `params` | 從路徑比對中取得的資訊 | 箱子還提供了一些方法,讓您無須自行處理檔案 IO。 -方法 | 描述 ---- | --- -`read` | 讀取檔案 -`readSync` | 同步讀取檔案 -`stat` | 讀取檔案狀態 -`statSync` | 同步讀取檔案狀態 -`render` | 渲染檔案 -`renderSync` | 同步渲染檔案 +| 方法 | 描述 | +| ------------ | ---------------- | +| `read` | 讀取檔案 | +| `readSync` | 同步讀取檔案 | +| `stat` | 讀取檔案狀態 | +| `statSync` | 同步讀取檔案狀態 | +| `render` | 渲染檔案 | +| `renderSync` | 同步渲染檔案 | [util.Pattern]: https://github.com/hexojs/hexo-util#patternrule diff --git a/source/zh-tw/api/console.md b/source/zh-tw/api/console.md index 4f359d75bc..f71660a008 100644 --- a/source/zh-tw/api/console.md +++ b/source/zh-tw/api/console.md @@ -1,21 +1,22 @@ --- title: 控制台(Console) --- + 控制台是 Hexo 與使用者之間溝通的橋樑。 ## 概要 -``` js -hexo.extend.console.register(name, desc, options, function(args){ +```js +hexo.extend.console.register(name, desc, options, function (args) { // ... }); ``` -參數 | 描述 ---- | --- -`name` | 名稱 -`desc` | 描述 -`options`| 選項 +| 參數 | 描述 | +| --------- | ---- | +| `name` | 名稱 | +| `desc` | 描述 | +| `options` | 選項 | 在函數中會傳入 `args` 參數,此參數是使用者在終端機所傳入的參數,是一個經 [Minimist] 解析的物件。 @@ -25,8 +26,10 @@ hexo.extend.console.register(name, desc, options, function(args){ 控制台的操作方法,例如: -``` js -{usage: '[layout] <title>'} +```js +{ + usage: "[layout] <title>"; +} // hexo new [layout] <title> ``` @@ -34,12 +37,12 @@ hexo.extend.console.register(name, desc, options, function(args){ 控制台各個參數的說明,例如: -``` js +```js { arguments: [ - {name: 'layout', desc: 'Post layout'}, - {name: 'title', desc: 'Post title'} - ] + { name: "layout", desc: "Post layout" }, + { name: "title", desc: "Post title" }, + ]; } ``` @@ -47,11 +50,9 @@ hexo.extend.console.register(name, desc, options, function(args){ 控制台的選項,例如: -``` js +```js { - options: [ - {name: '-r, --replace', desc: 'Replace existing files'} - ] + options: [{ name: "-r, --replace", desc: "Replace existing files" }]; } ``` @@ -61,10 +62,14 @@ hexo.extend.console.register(name, desc, options, function(args){ ## 範例 -``` js -hexo.extend.console.register('config', 'Display configuration', function(args){ - console.log(hexo.config); -}); +```js +hexo.extend.console.register( + "config", + "Display configuration", + function (args) { + console.log(hexo.config); + }, +); ``` [Minimist]: https://github.com/minimistjs/minimist diff --git a/source/zh-tw/api/deployer.md b/source/zh-tw/api/deployer.md index 2e428a5bda..ce850aa16d 100644 --- a/source/zh-tw/api/deployer.md +++ b/source/zh-tw/api/deployer.md @@ -1,12 +1,13 @@ --- title: 佈署器(Deployer) --- + 佈署器幫助使用者快速將網站佈署到遠端伺服器上,免去複雜的指令。 ## 概要 -``` js -hexo.extend.deployer.register(name, function(args){ +```js +hexo.extend.deployer.register(name, function (args) { // ... }); ``` diff --git a/source/zh-tw/api/events.md b/source/zh-tw/api/events.md index 2036c41f1b..0a9c50d7d4 100644 --- a/source/zh-tw/api/events.md +++ b/source/zh-tw/api/events.md @@ -1,6 +1,7 @@ --- title: 事件 --- + Hexo 繼承了 [EventEmitter],您可用 `on` 方法監聽 Hexo 所發佈的事件,亦可用 `emit` 方法對 Hexo 發佈事件,更詳細的說明請參閱 Node.js 的 API。 ### deployBefore @@ -27,16 +28,16 @@ Hexo 繼承了 [EventEmitter],您可用 `on` 方法監聽 Hexo 所發佈的事 在文章檔案建立完成後發佈。此事件會回傳資料參數。 -``` js -hexo.on('new', function(post){ - // +```js +hexo.on("new", function (post) { + // }); ``` -資料 | 描述 ---- | --- -`post.path` | 文章檔案的完整路徑 -`post.content` | 文章檔案的內容 +| 資料 | 描述 | +| -------------- | ------------------ | +| `post.path` | 文章檔案的完整路徑 | +| `post.content` | 文章檔案的內容 | ### processBefore diff --git a/source/zh-tw/api/filter.md b/source/zh-tw/api/filter.md index a838150f05..19c63ca92b 100644 --- a/source/zh-tw/api/filter.md +++ b/source/zh-tw/api/filter.md @@ -1,11 +1,12 @@ --- title: 過濾器(Filter) --- + 過濾器用於修改特定資料,Hexo 將資料依序傳給過濾器,而過濾器可以針對資料進行修改,這個概念是從 [WordPress](http://codex.wordpress.org/Plugin_API#Filters) 借來的。 ## 概要 -``` js +```js hexo.extend.filter.register(type, function() { // User configuration const { config } = this; @@ -22,69 +23,69 @@ hexo.extend.filter.register(type, function() { ## 執行過濾器 -``` js +```js hexo.extend.filter.exec(type, data, options); hexo.extend.filter.execSync(type, data, options); ``` -選項 | 描述 ---- | --- -`context` | Context -`args` | 參數。必須為陣列。 +| 選項 | 描述 | +| --------- | ------------------ | +| `context` | Context | +| `args` | 參數。必須為陣列。 | `data` 會作為第一個參數傳入每個過濾器,而您可在過濾器中透過回傳值改變下一個過濾器中的 `data`,如果什麼都沒回傳的話則會保持原本的 `data`。您還可使用 `args` 指定過濾器的其他參數。舉例來說: -``` js -hexo.extend.filter.register('test', function(data, arg1, arg2){ +```js +hexo.extend.filter.register("test", function (data, arg1, arg2) { // data === 'some data' // arg1 === 'foo' // arg2 === 'bar' - return 'something'; + return "something"; }); -hexo.extend.filter.register('test', function(data, arg1, arg2){ +hexo.extend.filter.register("test", function (data, arg1, arg2) { // data === 'something' }); -hexo.extend.filter.exec('test', 'some data', { - args: ['foo', 'bar'] +hexo.extend.filter.exec("test", "some data", { + args: ["foo", "bar"], }); ``` 您也可使用以下方法來執行過濾器: -``` js +```js hexo.execFilter(type, data, options); hexo.execFilterSync(type, data, options); ``` ## 移除過濾器 -``` js +```js hexo.extend.filter.unregister(type, filter); ``` **Example** -``` js +```js // Unregister a filter which is registered with named function const filterFn = (data) => { - data = 'something'; + data = "something"; return data; }; -hexo.extend.filter.register('example', filterFn); +hexo.extend.filter.register("example", filterFn); -hexo.extend.filter.unregister('example', filterFn); +hexo.extend.filter.unregister("example", filterFn); ``` -``` js +```js // Unregister a filter which is registered with commonjs module -hexo.extend.filter.register('example', require('path/to/filter')); +hexo.extend.filter.register("example", require("path/to/filter")); -hexo.extend.filter.unregister('example', require('path/to/filter')); +hexo.extend.filter.unregister("example", require("path/to/filter")); ``` ## 過濾器列表 @@ -97,8 +98,8 @@ hexo.extend.filter.unregister('example', require('path/to/filter')); 舉例來說,把標題轉為小寫: -``` js -hexo.extend.filter.register('before_post_render', function(data){ +```js +hexo.extend.filter.register("before_post_render", function (data) { data.title = data.title.toLowerCase(); return data; }); @@ -110,9 +111,12 @@ hexo.extend.filter.register('before_post_render', function(data){ 舉例來說,把 `@username` 取代為 Twitter 的使用者連結。 -``` js -hexo.extend.filter.register('after_post_render', function(data){ - data.content = data.content.replace(/@(\d+)/, '<a href="http://twitter.com/$1">#$1</a>'); +```js +hexo.extend.filter.register("after_post_render", function (data) { + data.content = data.content.replace( + /@(\d+)/, + '<a href="http://twitter.com/$1">#$1</a>', + ); return data; }); ``` @@ -121,8 +125,8 @@ hexo.extend.filter.register('after_post_render', function(data){ 在 Hexo 即將結束時執行,也就是在 `hexo.exit` 被呼叫後執行。 -``` js -hexo.extend.filter.register('before_exit', function(){ +```js +hexo.extend.filter.register("before_exit", function () { // ... }); ``` @@ -131,8 +135,8 @@ hexo.extend.filter.register('before_exit', function(){ 在產生器執行開始前執行。 -``` js -hexo.extend.filter.register('before_generate', function(){ +```js +hexo.extend.filter.register("before_generate", function () { // ... }); ``` @@ -141,8 +145,8 @@ hexo.extend.filter.register('before_generate', function(){ 在產生器執行結束後執行。 -``` js -hexo.extend.filter.register('after_generate', function(){ +```js +hexo.extend.filter.register("after_generate", function () { // ... }); ``` @@ -153,8 +157,8 @@ hexo.extend.filter.register('after_generate', function(){ 舉例來說,在模板的區域變數中新增目前的時間: -``` js -hexo.extend.filter.register('template_locals', function(locals){ +```js +hexo.extend.filter.register("template_locals", function (locals) { locals.now = Date.now(); return locals; }); @@ -164,8 +168,8 @@ hexo.extend.filter.register('template_locals', function(locals){ 在 Hexo 初始化完成後執行,也就是在 `hexo.init` 執行完成後執行。 -``` js -hexo.extend.filter.register('after_init', function(){ +```js +hexo.extend.filter.register("after_init", function () { // ... }); ``` @@ -174,8 +178,8 @@ hexo.extend.filter.register('after_init', function(){ 用來決定新建文章的路徑,在建立文章時執行。 -``` js -hexo.extend.filter.register('new_post_path', function(data, replace){ +```js +hexo.extend.filter.register("new_post_path", function (data, replace) { // ... }); ``` @@ -184,8 +188,8 @@ hexo.extend.filter.register('new_post_path', function(data, replace){ 用來決定文章的永久連結。 -``` js -hexo.extend.filter.register('post_permalink', function(data){ +```js +hexo.extend.filter.register("post_permalink", function (data) { // ... }); ``` @@ -200,10 +204,10 @@ hexo.extend.filter.register('post_permalink', function(data){ 舉例來說,在回應標頭中新增 `X-Powered-By: Hexo`。 -``` js -hexo.extend.filter.register('server_middleware', function(app){ - app.use(function(req, res, next){ - res.setHeader('X-Powered-By', 'Hexo'); +```js +hexo.extend.filter.register("server_middleware", function (app) { + app.use(function (req, res, next) { + res.setHeader("X-Powered-By", "Hexo"); next(); }); }); diff --git a/source/zh-tw/api/generator.md b/source/zh-tw/api/generator.md index 77ea1ab8c7..1b3d0b6411 100644 --- a/source/zh-tw/api/generator.md +++ b/source/zh-tw/api/generator.md @@ -1,12 +1,13 @@ --- title: 產生器(Generator) --- + 產生器根據處理後的原始檔案建立路由。 ## 概要 -``` js -hexo.extend.generator.register(name, function(locals){ +```js +hexo.extend.generator.register(name, function (locals) { // ... }); ``` @@ -15,27 +16,27 @@ hexo.extend.generator.register(name, function(locals){ ## 更新路由 -``` js -hexo.extend.generator.register('test', function(locals){ +```js +hexo.extend.generator.register("test", function (locals) { // Object return { - path: 'foo', - data: 'foo' + path: "foo", + data: "foo", }; - + // Array return [ - {path: 'foo', data: 'foo'}, - {path: 'bar', data: 'bar'} + { path: "foo", data: "foo" }, + { path: "bar", data: "bar" }, ]; }); ``` -屬性 | 描述 ---- | --- -`path` | 路徑。不可包含開頭的 `/`。 -`data` | 資料 -`layout` | 佈局。指定用於渲染的模板,可為字串或陣列,如果省略此屬性的話則會直接輸出 `data`。 +| 屬性 | 描述 | +| -------- | --------------------------------------------------------------------------------- | +| `path` | 路徑。不可包含開頭的 `/`。 | +| `data` | 資料 | +| `layout` | 佈局。指定用於渲染的模板,可為字串或陣列,如果省略此屬性的話則會直接輸出 `data`。 | 在原始檔案更新時,Hexo 會執行所有產生器並重建路由,**請直接回傳資料,不要直接操作路由**。 @@ -47,13 +48,13 @@ hexo.extend.generator.register('test', function(locals){ 然後,設定 `layout` 屬性好讓 Hexo 使用主題模板來渲染,在此例中同時設定了兩個佈局,當 `archive` 佈局不存在時,會繼續嘗試 `index` 佈局。 -``` js -hexo.extend.generator.register('archive', function(locals){ +```js +hexo.extend.generator.register("archive", function (locals) { return { - path: 'archives/index.html', + path: "archives/index.html", data: locals.posts, - layout: ['archive', 'index'] - } + layout: ["archive", "index"], + }; }); ``` @@ -61,14 +62,14 @@ hexo.extend.generator.register('archive', function(locals){ 您可透過 [hexo-pagination] 這個方便的官方工具程式來輕鬆建立分頁彙整。 -``` js -var pagination = require('hexo-pagination'); +```js +var pagination = require("hexo-pagination"); -hexo.extend.generator.register('archive', function(locals){ - return pagination('archives/index.html', locals.posts, { +hexo.extend.generator.register("archive", function (locals) { + return pagination("archives/index.html", locals.posts, { perPage: 10, - layout: ['archive', 'index'], - data: {} + layout: ["archive", "index"], + data: {}, }); }); ``` @@ -77,13 +78,13 @@ hexo.extend.generator.register('archive', function(locals){ 遍歷 `locals.posts` 中的所有文章並產生所有文章的路由。 -``` js -hexo.extend.generator.register('post', function(locals){ - return locals.posts.map(function(post){ +```js +hexo.extend.generator.register("post", function (locals) { + return locals.posts.map(function (post) { return { path: post.path, data: post, - layout: 'post' + layout: "post", }; }); }); @@ -93,15 +94,15 @@ hexo.extend.generator.register('post', function(locals){ 這次不直接在 `data` 中傳回資料而是傳回一個函數,如此一來這個路由唯有在使用時才會建立 `fs.ReadStream`。 -``` js -var fs = require('hexo-fs'); +```js +var fs = require("hexo-fs"); -hexo.extend.generator.register('asset', function(locals){ +hexo.extend.generator.register("asset", function (locals) { return { - path: 'file.txt', - data: function(){ - return fs.createReadStream('path/to/file.txt') - } + path: "file.txt", + data: function () { + return fs.createReadStream("path/to/file.txt"); + }, }; }); ``` diff --git a/source/zh-tw/api/helper.md b/source/zh-tw/api/helper.md index 5a45b09ed8..2c09cd9b11 100644 --- a/source/zh-tw/api/helper.md +++ b/source/zh-tw/api/helper.md @@ -1,25 +1,26 @@ --- title: 輔助函數(Helper) --- + 輔助函數幫助您在模板中快速插入內容,建議您把複雜的程式碼放在輔助函數而非模板中。 ## 概要 -``` js -hexo.extend.helper.register(name, function(){ +```js +hexo.extend.helper.register(name, function () { // ... }); ``` ## 範例 -``` js -hexo.extend.helper.register('js', function(path){ +```js +hexo.extend.helper.register("js", function (path) { return '<script src="' + path + '"></script>'; }); ``` -``` js +```js <%- js('script.js') %> // <script src="script.js"></script> ``` @@ -34,8 +35,8 @@ hexo.extend.helper.register('js', function(path){ All helpers are executed in the same context. For example, to use [`url_for()`](/docs/helpers#url-for) inside a custom helper: -``` js -hexo.extend.helper.register('lorem', function(path) { +```js +hexo.extend.helper.register("lorem", function (path) { return '<script src="' + this.url_for(path) + '"></script>'; }); ``` @@ -44,6 +45,6 @@ hexo.extend.helper.register('lorem', function(path) { `hexo.extend.helper.get` 會返回一個指定名字的 helper,但是你還需要一個 `bind(hexo)`,就像這樣: -``` js -const url_for = hexo.extend.helper.get('url_for').bind(hexo); +```js +const url_for = hexo.extend.helper.get("url_for").bind(hexo); ``` diff --git a/source/zh-tw/api/index.md b/source/zh-tw/api/index.md index f01837fd7c..6f9637dc40 100644 --- a/source/zh-tw/api/index.md +++ b/source/zh-tw/api/index.md @@ -1,6 +1,7 @@ --- title: API --- + 本文件提供您更豐富的 API 資訊,使您更容易修改 Hexo 原始碼或撰寫外掛。如果您只是想要查詢關於 Hexo 的基本使用方法,請參閱 [文件](../docs/)。 在開始之前,請注意本文件僅適用於 Hexo 3 及以上版本。 @@ -9,21 +10,21 @@ title: API 首先,我們必須建立一個 Hexo 實例(instance),第一個參數是網站的根目錄,也就是 `base_dir`,而第二個參數則是初始化的選項。接著執行 `init` 方法後,Hexo 會載入外掛及配置檔案。 -``` js -var Hexo = require('hexo'); +```js +var Hexo = require("hexo"); var hexo = new Hexo(process.cwd(), {}); -hexo.init().then(function(){ +hexo.init().then(function () { // ... }); ``` -選項 | 描述 | 預設值 ---- | --- | --- -`debug` | 開啟除錯模式。在終端機中顯示除錯訊息,並在根目錄中儲存 `debug.log` 記錄檔。| `false` -`safe` | 開啟安全模式。不要載入任何外掛。| `false` -`silent` | 開啟安靜模式。不要在終端機中顯示任何訊息。| `false` -`config` | 指定配置檔案的路徑。| `_config.yml` +| 選項 | 描述 | 預設值 | +| -------- | --------------------------------------------------------------------------- | ------------- | +| `debug` | 開啟除錯模式。在終端機中顯示除錯訊息,並在根目錄中儲存 `debug.log` 記錄檔。 | `false` | +| `safe` | 開啟安全模式。不要載入任何外掛。 | `false` | +| `silent` | 開啟安靜模式。不要在終端機中顯示任何訊息。 | `false` | +| `config` | 指定配置檔案的路徑。 | `_config.yml` | ## 載入檔案 @@ -31,12 +32,12 @@ Hexo 提供了兩種方法來載入檔案:`load`, `watch`,前者用於載入 這兩個方法實際上所做的,就是載入檔案列表,並把檔案傳給相對應的處理器(Processor),當檔案全部處理完畢後,就執行產生器(Generator)來建立路由。 -``` js -hexo.load().then(function(){ +```js +hexo.load().then(function () { // ... }); -hexo.watch().then(function(){ +hexo.watch().then(function () { // 之後可呼叫 hexo.unwatch() 停止檔案監看 }); ``` @@ -45,8 +46,8 @@ hexo.watch().then(function(){ 您可透過 `call` 方法來呼叫控制台(Console),第一個參數是控制台的名稱,而第二個參數是選項,根據不同控制台而有所不同。 -``` js -hexo.call('generate', {}).then(function(){ +```js +hexo.call("generate", {}).then(function () { // ... }); ``` @@ -55,10 +56,13 @@ hexo.call('generate', {}).then(function(){ 當指令完畢後,請執行 `exit` 方法讓 Hexo 完成結束前的準備工作(如儲存資料庫)。 -``` js -hexo.call('generate').then(function(){ - return hexo.exit(); -}).catch(function(err){ - return hexo.exit(err); -}); +```js +hexo + .call("generate") + .then(function () { + return hexo.exit(); + }) + .catch(function (err) { + return hexo.exit(err); + }); ``` diff --git a/source/zh-tw/api/injector.md b/source/zh-tw/api/injector.md index 80d43a2085..a1200bf9d7 100644 --- a/source/zh-tw/api/injector.md +++ b/source/zh-tw/api/injector.md @@ -7,7 +7,7 @@ An injector is used to add static code snippet to the `<head>` or/and `<body>` o ## Synopsis ```js -hexo.extend.injector.register(entry, value, to) +hexo.extend.injector.register(entry, value, to); ``` ### entry `<string>` @@ -40,24 +40,34 @@ Which page will code snippets being injected. - `tag`: Only inject to tag pages (which has `is_tag()` helper being `true`) - Custom layout name could be used as well, see [Writing - Layout](/docs/writing#Layout). ----- +--- There are other internal functions, see [hexojs/hexo#4049](https://github.com/hexojs/hexo/pull/4049) for more details. ## Example ```js -const css = hexo.extend.helper.get('css').bind(hexo); -const js = hexo.extend.helper.get('js').bind(hexo); - -hexo.extend.injector.register('head_end', () => { - return css('https://cdn.jsdelivr.net/npm/aplayer@1.10.1/dist/APlayer.min.css'); -}, 'music'); - -hexo.extend.injector.register('body_end', '<script src="https://cdn.jsdelivr.net/npm/aplayer@1.10.1/dist/APlayer.min.js">', 'music'); - -hexo.extend.injector.register('body_end', () => { - return js('/js/jquery.js'); +const css = hexo.extend.helper.get("css").bind(hexo); +const js = hexo.extend.helper.get("js").bind(hexo); + +hexo.extend.injector.register( + "head_end", + () => { + return css( + "https://cdn.jsdelivr.net/npm/aplayer@1.10.1/dist/APlayer.min.css", + ); + }, + "music", +); + +hexo.extend.injector.register( + "body_end", + '<script src="https://cdn.jsdelivr.net/npm/aplayer@1.10.1/dist/APlayer.min.js">', + "music", +); + +hexo.extend.injector.register("body_end", () => { + return js("/js/jquery.js"); }); ``` @@ -69,10 +79,10 @@ Use any of the following options: 1. -``` js -const css = hexo.extend.helper.get('css').bind(hexo); +```js +const css = hexo.extend.helper.get("css").bind(hexo); -hexo.extend.injector.register('head_end', () => { +hexo.extend.injector.register("head_end", () => { const { cssPath } = hexo.config.fooPlugin; return css(cssPath); }); @@ -80,23 +90,23 @@ hexo.extend.injector.register('head_end', () => { 2. -``` js index.js +```js index.js /* global hexo */ -hexo.extend.injector.register('head_end', require('./lib/inject').bind(hexo)) +hexo.extend.injector.register("head_end", require("./lib/inject").bind(hexo)); ``` -``` js lib/inject.js +```js lib/inject.js module.exports = function () { - const css = this.extend.helper.get('css'); + const css = this.extend.helper.get("css"); const { cssPath } = this.config.fooPlugin; return css(cssPath); -} +}; ``` -``` js lib/inject.js +```js lib/inject.js function injectFn() { - const css = this.extend.helper.get('css'); + const css = this.extend.helper.get("css"); const { cssPath } = this.config.fooPlugin; return css(cssPath); } @@ -106,23 +116,23 @@ module.exports = injectFn; 3. -``` js index.js +```js index.js /* global hexo */ -hexo.extend.injector.register('head_end', require('./lib/inject')(hexo)) +hexo.extend.injector.register("head_end", require("./lib/inject")(hexo)); ``` -``` js lib/inject.js +```js lib/inject.js module.exports = (hexo) => () => { - const css = hexo.extend.helper.get('css').bind(hexo); + const css = hexo.extend.helper.get("css").bind(hexo); const { cssPath } = hexo.config.fooPlugin; return css(cssPath); }; ``` -``` js lib/inject.js +```js lib/inject.js const injectFn = (hexo) => { - const css = hexo.extend.helper.get('css').bind(hexo); + const css = hexo.extend.helper.get("css").bind(hexo); const { cssPath } = hexo.config.fooPlugin; return css(cssPath); }; diff --git a/source/zh-tw/api/locals.md b/source/zh-tw/api/locals.md index cf187392b8..fe40009c2e 100644 --- a/source/zh-tw/api/locals.md +++ b/source/zh-tw/api/locals.md @@ -1,26 +1,27 @@ --- title: 區域變數 --- + 區域變數用於模版渲染,也就是模版中的 `site` 變數。 ## 預設變數 -變數 | 描述 ---- | --- -`posts` | 所有文章 -`pages` | 所有分頁 -`categories` | 所有分類 -`tags` | 所有標籤 +| 變數 | 描述 | +| ------------ | -------- | +| `posts` | 所有文章 | +| `pages` | 所有分頁 | +| `categories` | 所有分類 | +| `tags` | 所有標籤 | ## 取得變數 -``` js -hexo.locals.get('posts') +```js +hexo.locals.get("posts"); ``` ## 設定變數 -``` js +```js hexo.locals.set('posts', function(){ return ... }); @@ -28,18 +29,18 @@ hexo.locals.set('posts', function(){ ## 移除變數 -``` js -hexo.locals.remove('posts'); +```js +hexo.locals.remove("posts"); ``` ## 取得所有變數 -``` js +```js hexo.locals.toObject(); ``` ## 清除快取 -``` js +```js hexo.locals.invalidate(); ``` diff --git a/source/zh-tw/api/migrator.md b/source/zh-tw/api/migrator.md index 35cda325ce..6197fc519d 100644 --- a/source/zh-tw/api/migrator.md +++ b/source/zh-tw/api/migrator.md @@ -1,12 +1,13 @@ --- title: 轉移器(Migrator) --- + 轉移器幫助使用者從其他系統轉移到 Hexo。 ## 概要 -``` js -hexo.extend.migrator.register(name, function(args){ +```js +hexo.extend.migrator.register(name, function (args) { // ... }); ``` diff --git a/source/zh-tw/api/posts.md b/source/zh-tw/api/posts.md index 18fa264f3c..555e13474f 100644 --- a/source/zh-tw/api/posts.md +++ b/source/zh-tw/api/posts.md @@ -1,55 +1,56 @@ --- title: 文章 --- + ## 建立文章 -``` js +```js hexo.post.create(data, replace); ``` -參數 | 描述 ---- | --- -`data` | 資料 -`replace` | 取代現有檔案 +| 參數 | 描述 | +| --------- | ------------ | +| `data` | 資料 | +| `replace` | 取代現有檔案 | 您可在資料中指定文章的屬性,除了以下的屬性之外,其他屬性也會被加到 front-matter 中。 -資料 | 描述 ---- | --- -`title` | 標題 -`slug` | 網址 -`layout` | 佈局。預設為 `default_layout` 設定。 -`path` | 路徑。預設會根據 `new_post_path` 設定建構文章路徑。 -`date` | 日期。預設為目前時間。 +| 資料 | 描述 | +| -------- | --------------------------------------------------- | +| `title` | 標題 | +| `slug` | 網址 | +| `layout` | 佈局。預設為 `default_layout` 設定。 | +| `path` | 路徑。預設會根據 `new_post_path` 設定建構文章路徑。 | +| `date` | 日期。預設為目前時間。 | ## 發佈草稿 -``` js +```js hexo.post.publish(data, replace); ``` -參數 | 描述 ---- | --- -`data` | 資料 -`replace` | 取代現有檔案 +| 參數 | 描述 | +| --------- | ------------ | +| `data` | 資料 | +| `replace` | 取代現有檔案 | 您可在資料中指定文章的屬性,除了以下的屬性之外,其他屬性也會被加到 front-matter 中。 -資料 | 描述 ---- | --- -`slug` | 檔案名稱(必須) -`layout` | 佈局。預設為 `default_layout` 設定。 +| 資料 | 描述 | +| -------- | ------------------------------------ | +| `slug` | 檔案名稱(必須) | +| `layout` | 佈局。預設為 `default_layout` 設定。 | ## 渲染 -``` js +```js hexo.post.render(source, data); ``` -參數 | 描述 ---- | --- -`source` | 檔案的完整路徑(可忽略) -`data` | 資料 +| 參數 | 描述 | +| -------- | ------------------------ | +| `source` | 檔案的完整路徑(可忽略) | +| `data` | 資料 | 資料中必須包含 `content` 屬性,如果沒有的話,會試著讀取原始檔案。此函數的執行順序為: diff --git a/source/zh-tw/api/processor.md b/source/zh-tw/api/processor.md index e6d6873fbc..5e6fa53501 100644 --- a/source/zh-tw/api/processor.md +++ b/source/zh-tw/api/processor.md @@ -1,12 +1,13 @@ --- title: 處理器(Processor) --- + 處理器用於處理 `source` 資料夾內的原始檔案。 ## 概要 -``` js -hexo.extend.processor.register(rule, function(file){ +```js +hexo.extend.processor.register(rule, function (file) { // ... }); ``` diff --git a/source/zh-tw/api/renderer.md b/source/zh-tw/api/renderer.md index 5358a73db2..e5ef1cf1df 100644 --- a/source/zh-tw/api/renderer.md +++ b/source/zh-tw/api/renderer.md @@ -1,70 +1,85 @@ --- title: 渲染引擎(Renderer) --- + 渲染引擎用於渲染內容。 ## 概要 -``` js -hexo.extend.renderer.register(name, output, function(data, options){ - // ... -}, sync); +```js +hexo.extend.renderer.register( + name, + output, + function (data, options) { + // ... + }, + sync, +); ``` -參數 | 描述 ---- | --- -`name` | 輸入的副檔名(小寫,不含開頭的 `.`) -`output` | 輸出的副檔名(小寫,不含開頭的 `.`) -`sync` | 同步模式 +| 參數 | 描述 | +| -------- | ------------------------------------ | +| `name` | 輸入的副檔名(小寫,不含開頭的 `.`) | +| `output` | 輸出的副檔名(小寫,不含開頭的 `.`) | +| `sync` | 同步模式 | 渲染函數中會傳入兩個參數: -參數 | 描述 ---- | --- -`data` | 包含兩個屬性:檔案路徑 `path` 和檔案內容 `text`。`path` 不一定存在。 -`option` | 選項 +| 參數 | 描述 | +| -------- | -------------------------------------------------------------------- | +| `data` | 包含兩個屬性:檔案路徑 `path` 和檔案內容 `text`。`path` 不一定存在。 | +| `option` | 選項 | ## 範例 ### 非同步模式 -``` js -var stylus = require('stylus'); +```js +var stylus = require("stylus"); // Callback -hexo.extend.renderer.register('styl', 'css', function(data, options, callback){ - stylus(data.text).set('filename', data.path).render(callback); -}); +hexo.extend.renderer.register( + "styl", + "css", + function (data, options, callback) { + stylus(data.text).set("filename", data.path).render(callback); + }, +); // Promise -hexo.extend.renderer.register('styl', 'css', function(data, options){ - return new Promise(function(resolve, reject){ - resolve('test'); +hexo.extend.renderer.register("styl", "css", function (data, options) { + return new Promise(function (resolve, reject) { + resolve("test"); }); }); ``` ### 同步模式 -``` js -var ejs = require('ejs'); - -hexo.extend.renderer.register('ejs', 'html', function(data, options){ - options.filename = data.path; - return ejs.render(data.text, options); -}, true); +```js +var ejs = require("ejs"); + +hexo.extend.renderer.register( + "ejs", + "html", + function (data, options) { + options.filename = data.path; + return ejs.render(data.text, options); + }, + true, +); ``` ### Disable Nunjucks tags Nunjucks tags `{{ }}` or `{% %}` (utilized by [tag plugin](/docs/tag-plugins)) are processed by default, to disable: -``` js +```js function lessFn(data, options) { // do something } -lessFn.disableNunjucks = true +lessFn.disableNunjucks = true; -hexo.extend.renderer.register('less', 'css', lessFn); +hexo.extend.renderer.register("less", "css", lessFn); ``` diff --git a/source/zh-tw/api/rendering.md b/source/zh-tw/api/rendering.md index 4b97f2335d..49165ba81d 100644 --- a/source/zh-tw/api/rendering.md +++ b/source/zh-tw/api/rendering.md @@ -1,14 +1,15 @@ --- title: 渲染 --- + 在 Hexo 中,有兩個方法可用於渲染檔案或字串,分別是非同步的 `hexo.render.render` 和同步的 `hexo.render.renderSync`,這兩個方法的使用方式十分類似,因此以下僅舉非同步的 `hexo.render.render` 為例。 ## 渲染字串 在渲染字串時,您必須指定 `engine`,如此一來 Hexo 才知道該選擇哪個渲染引擎來渲染。 -``` js -hexo.render.render({text: 'example', engine: 'swig'}).then(function(result){ +```js +hexo.render.render({ text: "example", engine: "swig" }).then(function (result) { // ... }); ``` @@ -17,8 +18,8 @@ hexo.render.render({text: 'example', engine: 'swig'}).then(function(result){ 在渲染檔案時,您無須指定 `engine`,Hexo 會自動從副檔名猜測所要使用的渲染引擎,當然您也可使用 `engine` 指定。 -``` js -hexo.render.render({path: 'path/to/file.swig'}).then(function(result){ +```js +hexo.render.render({ path: "path/to/file.swig" }).then(function (result) { // ... }); ``` @@ -27,8 +28,8 @@ hexo.render.render({path: 'path/to/file.swig'}).then(function(result){ 在渲染時,您可在第二個參數中代入選項。 -``` js -hexo.render.render({text: ''}, {foo: 'foo'}).then(function(result){ +```js +hexo.render.render({ text: "" }, { foo: "foo" }).then(function (result) { // ... }); ``` @@ -37,10 +38,10 @@ hexo.render.render({text: ''}, {foo: 'foo'}).then(function(result){ 在渲染完成後,Hexo 會自動執行相對應的 `after_render` 過濾器,舉例來說,我們可透過這個功能實作 JavaScript 壓縮。 -``` js -var UglifyJS = require('uglify-js'); +```js +var UglifyJS = require("uglify-js"); -hexo.extend.filter.register('after_render:js', function(str, data){ +hexo.extend.filter.register("after_render:js", function (str, data) { var result = UglifyJS.minify(str); return result.code; }); @@ -50,30 +51,30 @@ hexo.extend.filter.register('after_render:js', function(str, data){ 您可透過 `isRenderable` 或 `isRenderableSync` 兩個方法檢查檔案路徑是否可被渲染,只有在相對應的渲染器(renderer)已註冊的情況下才會返回 true。 -``` js -hexo.render.isRenderable('layout.swig') // true -hexo.render.isRenderable('image.png') // false +```js +hexo.render.isRenderable("layout.swig"); // true +hexo.render.isRenderable("image.png"); // false ``` ## 取得檔案的輸出副檔名 您可透過 `getOutput` 方法取得檔案路徑輸出後的副檔名,如果檔案無法渲染,則會返回空字串。 -``` js -hexo.render.getOutput('layout.swig') // html -hexo.render.getOutput('image.png') // ''' +```js +hexo.render.getOutput("layout.swig"); // html +hexo.render.getOutput("image.png"); // ''' ``` ## Disable Nunjucks tags If you are not using a [tag plugin](/docs/tag-plugins) and want to use `{{ }}` or `{% %}` in your post without using content [escaping](/docs/troubleshooting#Escape-Contents), you can disable processing of Nunjucks tag in existing renderer by: -``` js +```js // following example only applies to '.md' file extension // you may need to cover other extensions, e.g. '.markdown', '.mkd', etc -const renderer = hexo.render.renderer.get('md') +const renderer = hexo.render.renderer.get("md"); if (renderer) { - renderer.disableNunjucks = true - hexo.extend.renderer.register('md', 'html', renderer) + renderer.disableNunjucks = true; + hexo.extend.renderer.register("md", "html", renderer); } ``` diff --git a/source/zh-tw/api/router.md b/source/zh-tw/api/router.md index cbeb02d7d4..d0e899c8da 100644 --- a/source/zh-tw/api/router.md +++ b/source/zh-tw/api/router.md @@ -1,15 +1,16 @@ --- title: 路由 --- + 路由儲存了網站中所用到的所有路徑。 ## 取得路徑 `get` 方法會傳回一個 [Stream],例如把該路徑的資料儲存到某個指定位置。 -``` js -var data = hexo.route.get('index.html'); -var dest = fs.createWriteStream('somewhere'); +```js +var data = hexo.route.get("index.html"); +var dest = fs.createWriteStream("somewhere"); data.pipe(dest); ``` @@ -18,32 +19,32 @@ data.pipe(dest); 您可在 `set` 方法中使用字串、[Buffer] 或函數,如下: -``` js +```js // String -hexo.route.set('index.html', 'index') +hexo.route.set("index.html", "index"); // Buffer -hexo.route.set('index.html', new Buffer('index')); +hexo.route.set("index.html", new Buffer("index")); // Function (Promise) -hexo.route.set('index.html', function(){ - return new Promise(function(resolve, reject){ - resolve('index'); +hexo.route.set("index.html", function () { + return new Promise(function (resolve, reject) { + resolve("index"); }); }); // Function (Callback) -hexo.route.set('index.html', function(callback){ - callback(null, 'index'); +hexo.route.set("index.html", function (callback) { + callback(null, "index"); }); ``` 您還可設定該路徑是否更新,這樣在生成檔案時便能忽略未更動的檔案,加快生成時間。 -``` js -hexo.route.set('index.html', { - data: 'index', - modified: false +```js +hexo.route.set("index.html", { + data: "index", + modified: false, }); // hexo.route.isModified('index.html') => false @@ -51,13 +52,13 @@ hexo.route.set('index.html', { ## 移除路徑 -``` js -hexo.route.remove('index.html'); +```js +hexo.route.remove("index.html"); ``` ## 取得路由表 -``` js +```js hexo.route.list(); ``` @@ -65,8 +66,8 @@ hexo.route.list(); `format` 方法可將字串轉為合法的路徑。 -``` js -hexo.route.format('archives/'); +```js +hexo.route.format("archives/"); // archives/index.html ``` diff --git a/source/zh-tw/api/scaffolds.md b/source/zh-tw/api/scaffolds.md index 47038b092e..ab9fd20335 100644 --- a/source/zh-tw/api/scaffolds.md +++ b/source/zh-tw/api/scaffolds.md @@ -1,20 +1,21 @@ --- title: 鷹架(Scaffold) --- + ## 取得鷹架 -``` js +```js hexo.scaffold.get(name); ``` ## 設定鷹架 -``` js +```js hexo.scaffold.set(name, content); ``` ## 移除鷹架 -``` js +```js hexo.scaffold.remove(name); ``` diff --git a/source/zh-tw/api/tag.md b/source/zh-tw/api/tag.md index 8a1bc826df..129f5f11c6 100644 --- a/source/zh-tw/api/tag.md +++ b/source/zh-tw/api/tag.md @@ -1,14 +1,19 @@ --- title: 標籤外掛(Tag) --- + 標籤外掛幫助使用者在文章中快速插入內容。 ## 概要 -``` js -hexo.extend.tag.register(name, function(args, content){ - // ... -}, options); +```js +hexo.extend.tag.register( + name, + function (args, content) { + // ... + }, + options, +); ``` 標籤函數會傳入兩個參數:`args` 和 `content`,前者代表使用者在使用標籤外掛時傳入的參數,而後者則是標籤外掛所包覆的內容。 @@ -19,22 +24,22 @@ hexo.extend.tag.register(name, function(args, content){ Use `unregister()` to replace existing [tag plugins](/docs/tag-plugins) with custom functions. -``` js +```js hexo.extend.tag.unregister(name); ``` **Example** -``` js +```js const tagFn = (args, content) => { - content = 'something'; + content = "something"; return content; }; // https://hexo.io/docs/tag-plugins#YouTube -hexo.extend.tag.unregister('youtube'); +hexo.extend.tag.unregister("youtube"); -hexo.extend.tag.register('youtube', tagFn); +hexo.extend.tag.register("youtube", tagFn); ``` ## 選項 @@ -53,10 +58,14 @@ hexo.extend.tag.register('youtube', tagFn); 插入 Youtube 影片。 -``` js -hexo.extend.tag.register('youtube', function(args){ +```js +hexo.extend.tag.register("youtube", function (args) { var id = args[0]; - return '<div class="video-container"><iframe width="560" height="315" src="http://www.youtube.com/embed/' + id + '" frameborder="0" allowfullscreen></iframe></div>'; + return ( + '<div class="video-container"><iframe width="560" height="315" src="http://www.youtube.com/embed/' + + id + + '" frameborder="0" allowfullscreen></iframe></div>' + ); }); ``` @@ -64,29 +73,43 @@ hexo.extend.tag.register('youtube', function(args){ 插入 pull quote。 -``` js -hexo.extend.tag.register('pullquote', function(args, content){ - var className = args.join(' '); - return '<blockquote class="pullquote' + className + '">' + content + '</blockquote>'; -}, {ends: true}); +```js +hexo.extend.tag.register( + "pullquote", + function (args, content) { + var className = args.join(" "); + return ( + '<blockquote class="pullquote' + + className + + '">' + + content + + "</blockquote>" + ); + }, + { ends: true }, +); ``` ### 非同步渲染 插入檔案。 -``` js -var fs = require('hexo-fs'); -var pathFn = require('path'); - -hexo.extend.tag.register('include_code', function(args){ - var filename = args[0]; - var path = pathFn.join(hexo.source_dir, filename); - - return fs.readFile(path).then(function(content){ - return '<pre><code>' + content + '</code></pre>'; - }); -}, {async: true}); +```js +var fs = require("hexo-fs"); +var pathFn = require("path"); + +hexo.extend.tag.register( + "include_code", + function (args) { + var filename = args[0]; + var path = pathFn.join(hexo.source_dir, filename); + + return fs.readFile(path).then(function (content) { + return "<pre><code>" + content + "</code></pre>"; + }); + }, + { async: true }, +); ``` ## Front-matter and user configuration @@ -95,7 +118,7 @@ Any of the following options is valid: 1. -``` js +```js hexo.extend.tag.register('foo', function (args) { const [firstArg] = args; @@ -120,11 +143,11 @@ hexo.extend.tag.register('foo', function (args) { 2. -``` js index.js -hexo.extend.tag.register('foo', require('./lib/foo')(hexo)); +```js index.js +hexo.extend.tag.register("foo", require("./lib/foo")(hexo)); ``` -``` js lib/foo.js +```js lib/foo.js module.exports = hexo => { return function fooFn(args) { const [firstArg] = args; diff --git a/source/zh-tw/api/themes.md b/source/zh-tw/api/themes.md index 2d0306cb22..aaf3e9c375 100644 --- a/source/zh-tw/api/themes.md +++ b/source/zh-tw/api/themes.md @@ -1,23 +1,24 @@ --- title: 主題 --- + `hexo.theme` 除了繼承 [盒子](box.html) 外,還身兼儲存模板的功能。 ## 取得模板 -``` js +```js hexo.theme.getView(path); ``` ## 設定模板 -``` js +```js hexo.theme.setView(path, data); ``` ## 移除模板 -``` js +```js hexo.theme.removeView(path); ``` @@ -25,10 +26,10 @@ hexo.theme.removeView(path); 模板本身有兩個方法可供使用:`render` 和 `renderSync`,兩者功能一樣,只是前者為非同步函數,而後者為同步函數,因此以下僅以 `render` 舉例。 -``` js -var view = hexo.theme.getView('layout.swig'); +```js +var view = hexo.theme.getView("layout.swig"); -view.render({foo: 1, bar: 2}).then(function(result){ +view.render({ foo: 1, bar: 2 }).then(function (result) { // ... }); ``` diff --git a/source/zh-tw/docs/asset-folders.md b/source/zh-tw/docs/asset-folders.md index fa9502dced..5259cb8bad 100644 --- a/source/zh-tw/docs/asset-folders.md +++ b/source/zh-tw/docs/asset-folders.md @@ -1,9 +1,10 @@ --- title: 資產資料夾 --- + 資產(Asset)代表 `source` 資料夾中除了文章以外的所有檔案,例如圖片、CSS、JS 檔案等。Hexo 提供了一種更方便管理 Asset 的設定:`post_asset_folder`。 -``` yaml +```yaml post_asset_folder: true ``` @@ -25,7 +26,7 @@ Hexo 3 新增了幾個[外掛](/docs/tag-plugins#Include-Assets),讓您更方 如需啟用: -``` yml _config.yml +```yml _config.yml post_asset_folder: true marked: prependRoot: true diff --git a/source/zh-tw/docs/commands.md b/source/zh-tw/docs/commands.md index c2d02541e5..c86e3470a5 100644 --- a/source/zh-tw/docs/commands.md +++ b/source/zh-tw/docs/commands.md @@ -6,7 +6,7 @@ title: 指令 ## init -``` bash +```bash $ hexo init [folder] ``` @@ -19,28 +19,28 @@ $ hexo init [folder] ## new -``` bash +```bash $ hexo new [layout] <title> ``` -建立一篇新的文章。如果沒有設定 `layout` 的話,則會使用 [_config.yml](configuration.html) 中的 `default_layout` 設定代替。如果標題包含空格的話,請使用引號括起來。 +建立一篇新的文章。如果沒有設定 `layout` 的話,則會使用 [\_config.yml](configuration.html) 中的 `default_layout` 設定代替。如果標題包含空格的話,請使用引號括起來。 ## generate -``` bash +```bash $ hexo generate ``` 產生靜態檔案。 -選項 | 描述 ---- | --- -`-d`, `--deploy` | 產生完成即部署網站 -`-w`, `--watch` | 監看檔案變更 +| 選項 | 描述 | +| ---------------- | ------------------ | +| `-d`, `--deploy` | 產生完成即部署網站 | +| `-w`, `--watch` | 監看檔案變更 | ## publish -``` bash +```bash $ hexo publish [layout] <filename> ``` @@ -48,45 +48,45 @@ $ hexo publish [layout] <filename> ## server -``` bash +```bash $ hexo server ``` 啟動伺服器,預設是 `http://localhost:4000/`。 -選項 | 描述 ---- | --- -`-p`, `--port` | 覆蓋連接埠設定 -`-s`, `--static` | 只使用靜態檔案 -`-l`, `--log` | 啟動記錄器,或覆蓋記錄格式 +| 選項 | 描述 | +| ---------------- | -------------------------- | +| `-p`, `--port` | 覆蓋連接埠設定 | +| `-s`, `--static` | 只使用靜態檔案 | +| `-l`, `--log` | 啟動記錄器,或覆蓋記錄格式 | ## deploy -``` bash +```bash $ hexo deploy ``` 部署網站。 -選項 | 描述 ---- | --- -`-g`, `--generate` | 部署網站前先產生靜態檔案 +| 選項 | 描述 | +| ------------------ | ------------------------ | +| `-g`, `--generate` | 部署網站前先產生靜態檔案 | ## render -``` bash +```bash $ hexo render <file> [file2] ... ``` 渲染檔案。 -選項 | 描述 ---- | --- -`-o`, `--output` | 輸出位置 +| 選項 | 描述 | +| ---------------- | -------- | +| `-o`, `--output` | 輸出位置 | ## migrate -``` bash +```bash $ hexo migrate <type> ``` @@ -94,7 +94,7 @@ $ hexo migrate <type> ## clean -``` bash +```bash $ hexo clean ``` @@ -102,7 +102,7 @@ $ hexo clean ## list -``` bash +```bash $ hexo list <type> ``` @@ -110,7 +110,7 @@ $ hexo list <type> ## version -``` bash +```bash $ hexo version ``` @@ -120,7 +120,7 @@ $ hexo version ### 安全模式 -``` bash +```bash $ hexo --safe ``` @@ -128,7 +128,7 @@ $ hexo --safe ### 除錯模式 -``` bash +```bash $ hexo --debug ``` @@ -136,7 +136,7 @@ $ hexo --debug ### 安靜模式 -``` bash +```bash $ hexo --silent ``` @@ -144,19 +144,19 @@ $ hexo --silent ### 自訂配置檔的路徑 -``` bash +```bash $ hexo --config custom.yml ``` 自訂配置檔的路徑而不是使用 `_config.yml`。此參數也接受以逗號分隔的 JSON 或 YAML 檔列表字串 (不得含有空格),它們將會被合併產生一個 `_multiconfig.yml`。 -``` bash +```bash $ hexo --config custom.yml,custom2.json ``` ### 顯示草稿 -``` bash +```bash $ hexo --draft ``` @@ -164,7 +164,7 @@ $ hexo --draft ### 自定 CWD -``` bash +```bash $ hexo --cwd /path/to/cwd ``` diff --git a/source/zh-tw/docs/configuration.md b/source/zh-tw/docs/configuration.md index 3c106bd776..d7f56ea67d 100644 --- a/source/zh-tw/docs/configuration.md +++ b/source/zh-tw/docs/configuration.md @@ -1,33 +1,34 @@ --- title: 配置 --- + 您可以在 `_config.yml` 或 [替代配置檔](#使用替代配置檔) 中修改網站配置。 {% youtube A0Enyn70jKU %} ### 網站 -設定 | 描述 ---- | --- -`title` | 網站標題 -`subtitle` | 網站副標題 -`description` | 網站描述 -`keywords` | 網站的關鍵詞。支援多個關鍵詞。 -`author` | 您的名字 -`language` | 網站使用的語言,參考 [2-lettter ISO-639-1 code](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes),預設為 `en` -`timezone` | 網站時區,Hexo 預設使用您電腦的時區,您可以在 [時區列表](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) 尋找適當的時區,例如 `America/New_York` 、 `Japan` 與 `UTC` +| 設定 | 描述 | +| ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `title` | 網站標題 | +| `subtitle` | 網站副標題 | +| `description` | 網站描述 | +| `keywords` | 網站的關鍵詞。支援多個關鍵詞。 | +| `author` | 您的名字 | +| `language` | 網站使用的語言,參考 [2-lettter ISO-639-1 code](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes),預設為 `en` | +| `timezone` | 網站時區,Hexo 預設使用您電腦的時區,您可以在 [時區列表](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) 尋找適當的時區,例如 `America/New_York` 、 `Japan` 與 `UTC` | ### 網址 -設定 | 描述 | 預設值 ---- | --- | --- -`url` | 網站的網址,must starts with `http://` or `https://` | -`root` | 網站的根目錄 | `url's pathname` -`permalink` | 文章 [永久連結](permalinks.html) 的格式 | `:year/:month/:day/:title/` -`permalink_defaults` | `permalink` 中各區段的預設值 | -`pretty_urls` | 改寫 [`permalink`](variables.html) 的值來美化 URL | -`pretty_urls.trailing_index` | 是否在永久鏈接中保留尾部的 `index.html`,設置為 `false` 時去除 | `true` -`pretty_urls.trailing_html` | 是否在永久鏈接中保留尾部的 `.html`, 設置為 `false` 時去除 (_對尾部的 `index.html`無效_) | `true` +| 設定 | 描述 | 預設值 | +| ---------------------------- | --------------------------------------------------------------------------------------- | --------------------------- | +| `url` | 網站的網址,must starts with `http://` or `https://` | +| `root` | 網站的根目錄 | `url's pathname` | +| `permalink` | 文章 [永久連結](permalinks.html) 的格式 | `:year/:month/:day/:title/` | +| `permalink_defaults` | `permalink` 中各區段的預設值 | +| `pretty_urls` | 改寫 [`permalink`](variables.html) 的值來美化 URL | +| `pretty_urls.trailing_index` | 是否在永久鏈接中保留尾部的 `index.html`,設置為 `false` 時去除 | `true` | +| `pretty_urls.trailing_html` | 是否在永久鏈接中保留尾部的 `.html`, 設置為 `false` 時去除 (_對尾部的 `index.html`無效_) | `true` | {% note info 網站存放在子目錄 %} 如果您的網站存放在子目錄中,例如 `http://example.org/blog`,請將您的 `url` 設為 `http://example.org/blog` 並把 `root` 設為 `/blog/`。 @@ -35,55 +36,55 @@ title: 配置 ### 目錄 -設定 | 描述 | 預設值 ---- | --- | --- -`source_dir` | 原始檔案資料夾,這個資料夾用於存放您的內容 | `source` -`public_dir` | 靜態檔案資料夾,這個資料夾用於存放建立完畢的檔案 | public -`tag_dir` | 標籤資料夾 | `tags` -`archive_dir` | 彙整資料夾 | `archives` -`category_dir` | 分類資料夾 | `categories` -`code_dir` | Include code 資料夾 | `downloads/code` -`i18n_dir` | 國際化(i18n)資料夾 | `:lang` -`skip_render` | 跳過指定檔案的渲染,您可使用 [glob 表達式](https://github.com/micromatch/micromatch#extended-globbing) 來配對路徑 | +| 設定 | 描述 | 預設值 | +| -------------- | ----------------------------------------------------------------------------------------------------------------- | ---------------- | +| `source_dir` | 原始檔案資料夾,這個資料夾用於存放您的內容 | `source` | +| `public_dir` | 靜態檔案資料夾,這個資料夾用於存放建立完畢的檔案 | public | +| `tag_dir` | 標籤資料夾 | `tags` | +| `archive_dir` | 彙整資料夾 | `archives` | +| `category_dir` | 分類資料夾 | `categories` | +| `code_dir` | Include code 資料夾 | `downloads/code` | +| `i18n_dir` | 國際化(i18n)資料夾 | `:lang` | +| `skip_render` | 跳過指定檔案的渲染,您可使用 [glob 表達式](https://github.com/micromatch/micromatch#extended-globbing) 來配對路徑 | ### 寫作 -設定 | 描述 | 預設值 ---- | --- | --- -`new_post_name` | 新文章的檔案名稱 | `:title.md` -`default_layout` | 預設佈局 | `post` -`auto_spacing` | 在西方文字與東方文字中加入空白 | `false` -`titlecase` | 把標題轉換為 title case | `false` -`external_link` | 在新頁籤中開啟連結 | `true` -`external_link.enable` | 在新頁籤中開啟連結 | `true` -`external_link.field` | 應用至整個 `site` 或僅只於 `post` | `site` -`external_link.exclude` | 主機名稱除外。適用於特指子網域,包含 `www` | `[]` -`filename_case` | 把檔案名稱轉換為: `1` 小寫或 `2` 大寫 | `0` -`render_drafts` | 顯示草稿 | `false` -`post_asset_folder` | 啟動 [Asset 資料夾](asset-folders.html) | `false` -`relative_link` | 把連結改為與根目錄的相對位址 | `false` -`future` | 顯示未來的文章 | `true` -`syntax_highlighter` | 程式碼區塊語法強調 (highlight) 設定,請見使用方式指南的[語法強調](/zh-tw/docs/syntax-highlight)區塊 | `highlight.js` -`highlight` | 程式碼區塊語法強調設定,請見使用方式指南的 [Highlight.js](/zh-tw/docs/syntax-highlight#Highlight-js) 區塊 | -`prismjs` | 程式碼區塊的設定,請見使用方式指南的 [PrismJS](/zh-tw/docs/syntax-highlight#PrismJS) 區塊 | +| 設定 | 描述 | 預設值 | +| ----------------------- | --------------------------------------------------------------------------------------------------------- | -------------- | +| `new_post_name` | 新文章的檔案名稱 | `:title.md` | +| `default_layout` | 預設佈局 | `post` | +| `auto_spacing` | 在西方文字與東方文字中加入空白 | `false` | +| `titlecase` | 把標題轉換為 title case | `false` | +| `external_link` | 在新頁籤中開啟連結 | `true` | +| `external_link.enable` | 在新頁籤中開啟連結 | `true` | +| `external_link.field` | 應用至整個 `site` 或僅只於 `post` | `site` | +| `external_link.exclude` | 主機名稱除外。適用於特指子網域,包含 `www` | `[]` | +| `filename_case` | 把檔案名稱轉換為: `1` 小寫或 `2` 大寫 | `0` | +| `render_drafts` | 顯示草稿 | `false` | +| `post_asset_folder` | 啟動 [Asset 資料夾](asset-folders.html) | `false` | +| `relative_link` | 把連結改為與根目錄的相對位址 | `false` | +| `future` | 顯示未來的文章 | `true` | +| `syntax_highlighter` | 程式碼區塊語法強調 (highlight) 設定,請見使用方式指南的[語法強調](/zh-tw/docs/syntax-highlight)區塊 | `highlight.js` | +| `highlight` | 程式碼區塊語法強調設定,請見使用方式指南的 [Highlight.js](/zh-tw/docs/syntax-highlight#Highlight-js) 區塊 | +| `prismjs` | 程式碼區塊的設定,請見使用方式指南的 [PrismJS](/zh-tw/docs/syntax-highlight#PrismJS) 區塊 | ### 分類 & 標籤 -設定 | 描述 | 預設值 ---- | --- | --- -`default_category` | 預設分類 | `uncategorized` -`category_map` | 分類別名 | -`tag_map` | 標籤別名 | +| 設定 | 描述 | 預設值 | +| ------------------ | -------- | --------------- | +| `default_category` | 預設分類 | `uncategorized` | +| `category_map` | 分類別名 | +| `tag_map` | 標籤別名 | ### 日期 / 時間格式 Hexo 使用 [Moment.js](http://momentjs.com/) 來解析和顯示時間。 -設定 | 描述 | 預設值 ---- | --- | --- -`date_format` | 日期格式 | `YYYY-MM-DD` -`time_format` | 時間格式 | `HH:mm:ss` -`updated_option` | 當 front-matter 沒有提供 [`updated`](/zh-tw/docs/variables#頁面變數) 的值則使用此值| `mtime` +| 設定 | 描述 | 預設值 | +| ---------------- | ----------------------------------------------------------------------------------- | ------------ | +| `date_format` | 日期格式 | `YYYY-MM-DD` | +| `time_format` | 時間格式 | `HH:mm:ss` | +| `updated_option` | 當 front-matter 沒有提供 [`updated`](/zh-tw/docs/variables#頁面變數) 的值則使用此值 | `mtime` | {% note info updated_option %} 當 front-matter 沒有提供 `updated` 值,則 `updated_option` 控制此值: @@ -97,17 +98,17 @@ Hexo 使用 [Moment.js](http://momentjs.com/) 來解析和顯示時間。 ### 分頁 -設定 | 描述 | 預設值 ---- | --- | --- -`per_page` | 一頁顯示的文章量 (`0` = 關閉分頁功能) | `10` -`pagination_dir` | 分頁目錄 | `page` +| 設定 | 描述 | 預設值 | +| ---------------- | ------------------------------------- | ------ | +| `per_page` | 一頁顯示的文章量 (`0` = 關閉分頁功能) | `10` | +| `pagination_dir` | 分頁目錄 | `page` | ### 擴充套件 -設定 | 描述 ---- | --- -`theme` | 使用主題名稱, 設為 `false` 表示關閉主題功能 -`deploy` | 佈署設定 +| 設定 | 描述 | +| -------- | ------------------------------------------- | +| `theme` | 使用主題名稱, 設為 `false` 表示關閉主題功能 | +| `deploy` | 佈署設定 | ### 包含/排除 檔案或資料夾 @@ -115,11 +116,11 @@ Hexo 會根據配置檔中 `include` / `exlude` 欄位設定,了解要 處理/ `include` 以及 `exclude` 選項只會應用在 `source/` 資料夾, 然而 `ignore` 選項則會應用在所有的資料夾。 -設定 | 描述 ---- | --- -`include` | Hexo 預設會忽略隱藏檔案與隱藏資料夾,但列在這個欄位中的檔案,Hexo 仍然會去處理 -`exclude` | 列在這裡的檔案將會被 Hexo 忽略 -`ignore` | 忽略檔案以及資料夾 +| 設定 | 描述 | +| --------- | ------------------------------------------------------------------------------ | +| `include` | Hexo 預設會忽略隱藏檔案與隱藏資料夾,但列在這個欄位中的檔案,Hexo 仍然會去處理 | +| `exclude` | 列在這裡的檔案將會被 Hexo 忽略 | +| `ignore` | 忽略檔案以及資料夾 | 範例: @@ -167,7 +168,7 @@ ignore: 範例: -``` bash +```bash # 使用自訂的 'custom.yml' 取代預設的 '_config.yml' $ hexo server --config custom.yml @@ -195,7 +196,7 @@ theme: "my-theme" theme_config: bio: "My awesome bio" foo: - bar: 'a' + bar: "a" ``` ```yml @@ -210,11 +211,11 @@ logo: "a-cool-image.png" ```json { - bio: "My awesome bio", - logo: "a-cool-image.png", - foo: { - bar: "a", - baz: "b" + "bio": "My awesome bio", + "logo": "a-cool-image.png", + "foo": { + "bar": "a", + "baz": "b" } } ``` @@ -234,7 +235,7 @@ theme: "my-theme" # _config.my-theme.yml bio: "My awesome bio" foo: - bar: 'a' + bar: "a" ``` ```yml @@ -249,11 +250,11 @@ logo: "a-cool-image.png" ```json { - bio: "My awesome bio", - logo: "a-cool-image.png", - foo: { - bar: "a", - baz: "b" + "bio": "My awesome bio", + "logo": "a-cool-image.png", + "foo": { + "bar": "a", + "baz": "b" } } ``` diff --git a/source/zh-tw/docs/contributing.md b/source/zh-tw/docs/contributing.md index ced7c769b9..477e257b54 100644 --- a/source/zh-tw/docs/contributing.md +++ b/source/zh-tw/docs/contributing.md @@ -25,7 +25,7 @@ title: 貢獻 1. Fork [hexojs/hexo] 2. 把檔案庫(repository)複製到電腦上,並安裝相依套件。 -``` bash +```bash $ git clone https://github.com/<username>/hexo.git $ cd hexo $ npm install @@ -34,7 +34,7 @@ $ git submodule update --init 3. 新增一個功能分支。 -``` bash +```bash $ git checkout -b new_feature ``` @@ -52,7 +52,7 @@ $ git push origin new_feature - 不要修改 `package.json` 的版本號。 - 只有在測試通過的情況下您的合併申請才會被核准,在提交前別忘了進行測試。 -``` bash +```bash $ npm test ``` @@ -69,7 +69,7 @@ Hexo 文件開放原始碼,您可以在 [hexojs/site] 找到原始碼。 1. Fork [hexojs/site] 2. 把檔案庫(repository)複製到電腦上,並安裝相依套件。 -``` bash +```bash $ npm install hexo-cli -g # If you don't have hexo-cli installed $ git clone https://github.com/<username>/site.git $ cd site @@ -78,7 +78,7 @@ $ npm install 3. 開始編輯文件,您可透過伺服器預覽變更。 -``` bash +```bash $ hexo server ``` diff --git a/source/zh-tw/docs/data-files.md b/source/zh-tw/docs/data-files.md index ae80a99819..f25c5f0870 100644 --- a/source/zh-tw/docs/data-files.md +++ b/source/zh-tw/docs/data-files.md @@ -1,11 +1,12 @@ --- title: 資料檔案 --- + 有時您可能需要在主題中使用某些資料,而這些資料並不在文章內,或是想要重複使用,那麼您可以考慮使用 Hexo 3 新增的「資料檔案」功能。此功能會載入 `source/_data` 內的 YAML 或 JSON 檔案,如此一來您便能在網站中使用。 舉例來說,在 `source/_data` 資料夾中新增 `menu.yml` 檔案: -``` yaml +```yaml Home: / Gallery: /gallery/ Archives: /archives/ diff --git a/source/zh-tw/docs/front-matter.md b/source/zh-tw/docs/front-matter.md index e106f33356..3168e23966 100644 --- a/source/zh-tw/docs/front-matter.md +++ b/source/zh-tw/docs/front-matter.md @@ -6,7 +6,7 @@ title: Front-matter Front-matter 是檔案最上方以 `---` 分隔的區域,用於指定個別檔案的變數,舉例來說: -``` yaml +```yaml --- title: Hello World date: 2013/7/13 20:46:25 @@ -15,24 +15,24 @@ date: 2013/7/13 20:46:25 以下是預先定義的設定,您可在模板中取得這些設定值並加以利用。 -設定 | 描述 | 預設值 ---- | --- | --- -`layout` | 佈局 | [`config.default_layout`](/zh-tw/docs/configuration#寫作) -`title` | 標題 | 文章的檔案名 -`date` | 建立日期 | 檔案建立日期 -`updated` | 更新日期 | 檔案更新日期 -`comments` | 開啟文章的留言功能 | `true` -`tags` | 標籤(不適用於分頁) | -`categories` | 分類(不適用於分頁)| -`permalink` | 覆蓋文章網址 | -`excerpt` | 純文字的頁面摘要。使用[這個外掛](/zh-tw/docs/tag-plugins#文章摘要)進行文字格式化。 | -`disableNunjucks` | 當啟用時,禁止 Nunjucks 標籤 `{{ }}`/`{% %}` 以及[標籤外掛](/zh-tw/docs/tag-plugins)的渲染功能 -`lang` | 設定語言並寫[自動偵測](/zh-tw/docs/internationalization#路徑) | 繼承自 `_config.yml` -`published` | 文章是否發布 | 在 `_posts` 中的文章為 `true`;而在 `_draft` 中的文章則為 `false` +| 設定 | 描述 | 預設值 | +| ----------------- | ---------------------------------------------------------------------------------------------- | ----------------------------------------------------------------- | +| `layout` | 佈局 | [`config.default_layout`](/zh-tw/docs/configuration#寫作) | +| `title` | 標題 | 文章的檔案名 | +| `date` | 建立日期 | 檔案建立日期 | +| `updated` | 更新日期 | 檔案更新日期 | +| `comments` | 開啟文章的留言功能 | `true` | +| `tags` | 標籤(不適用於分頁) | +| `categories` | 分類(不適用於分頁) | +| `permalink` | 覆蓋文章網址 | +| `excerpt` | 純文字的頁面摘要。使用[這個外掛](/zh-tw/docs/tag-plugins#文章摘要)進行文字格式化。 | +| `disableNunjucks` | 當啟用時,禁止 Nunjucks 標籤 `{{ }}`/`{% %}` 以及[標籤外掛](/zh-tw/docs/tag-plugins)的渲染功能 | +| `lang` | 設定語言並寫[自動偵測](/zh-tw/docs/internationalization#路徑) | 繼承自 `_config.yml` | +| `published` | 文章是否發布 | 在 `_posts` 中的文章為 `true`;而在 `_draft` 中的文章則為 `false` | ### 佈局 -依照 `_config.yml` 中所設定的 [`default_layout`]((/zh-tw/docs/configuration#寫作)) 值,預設的佈局為 `post`。當在文章中取消佈局 (`layout: false`),則不會為它套用主題。然而,這依然會在任意的渲染引擎 (renderer) 中渲染,若一個文章是用 Markdown 編寫且已經安裝了 Markdown 算圖引擎(如預設的[hexo-renderer-marked](https://github.com/hexojs/hexo-renderer-marked)),則會被渲染為 HTML。 +依照 `_config.yml` 中所設定的 [`default_layout`](/zh-tw/docs/configuration#寫作) 值,預設的佈局為 `post`。當在文章中取消佈局 (`layout: false`),則不會為它套用主題。然而,這依然會在任意的渲染引擎 (renderer) 中渲染,若一個文章是用 Markdown 編寫且已經安裝了 Markdown 算圖引擎(如預設的[hexo-renderer-marked](https://github.com/hexojs/hexo-renderer-marked)),則會被渲染為 HTML。 無論任何佈局,[標籤外掛](/zh-tw/docs/tag-plugins)一定會進行處理,除非禁止 `disableNunjucks` 的設定或是[渲染引擎](/zh-tw/api/renderer#Disable-Nunjucks-tags). @@ -40,28 +40,28 @@ date: 2013/7/13 20:46:25 分類和標籤只有文章才支援,您可以在 Front-matter 中設定。在其他系統中,分類和標籤可能聽起來很接近,但是在 Hexo 中有著決定性的差別:分類是有順序和階層性的,也就是說 `Foo, Bar` 不等於 `Bar, Foo`;而標籤沒有順序和階層。 -``` yaml +```yaml categories: -- Diary + - Diary tags: -- PS3 -- Games + - PS3 + - Games ``` 此外我們可以透過 list 來對一篇文章同時定義多個分類。 -``` yaml +```yaml categories: -- [Diary, PlayStation] -- [Diary, Games] -- [Life] + - [Diary, PlayStation] + - [Diary, Games] + - [Life] ``` ### JSON Front-matter 除了 YAML 外,你也可利用 JSON 來撰寫 Front-matter,只要將 `---` 代換成 `;;;` 即可。 -``` json +```json "title": "Hello World", "date": "2013/7/13 20:46:25" ;;; diff --git a/source/zh-tw/docs/generating.md b/source/zh-tw/docs/generating.md index 3dcd9594b6..48de162c65 100644 --- a/source/zh-tw/docs/generating.md +++ b/source/zh-tw/docs/generating.md @@ -1,9 +1,10 @@ --- title: 產生檔案 --- + 使用 Hexo 產生靜態檔案非常快速而且簡單。 -``` bash +```bash $ hexo generate ``` @@ -11,7 +12,7 @@ $ hexo generate Hexo 能夠監看檔案變更並立即重新產生靜態檔案,在建立時會比對檔案的 SHA1 checksum,只有變動的檔案才會寫入。 -``` bash +```bash $ hexo generate --watch ``` @@ -19,7 +20,7 @@ $ hexo generate --watch 您可執行下列的其中一個指令,讓 Hexo 在建立完畢後自動佈署網站,兩個指令的作用是相同的。 -``` bash +```bash $ hexo generate --deploy $ hexo deploy --generate ``` diff --git a/source/zh-tw/docs/github-pages.md b/source/zh-tw/docs/github-pages.md index 3c28892886..aa7db8be85 100755 --- a/source/zh-tw/docs/github-pages.md +++ b/source/zh-tw/docs/github-pages.md @@ -9,10 +9,11 @@ title: 在 GitHub Pages 上部署 Hexo - 將 `main` 分支 push 到 GitHub: - ``` - $ git push -u origin main - ``` - - 預設情況下 `public/` 不會被上傳(也不該被上傳),確認 `.gitignore` 檔案中包含一行 `public/`。整體資料夾結構應會與[範例儲存庫](https://github.com/hexojs/hexo-starter)極為相似。 + ``` + $ git push -u origin main + ``` + +- 預設情況下 `public/` 不會被上傳(也不該被上傳),確認 `.gitignore` 檔案中包含一行 `public/`。整體資料夾結構應會與[範例儲存庫](https://github.com/hexojs/hexo-starter)極為相似。 3. 使用 `node --version` 指令檢查你電腦上的 Node.js 版本,並記下該版本 (例如:`v20.y.z`) 4. 在儲存庫中前往 `Settings > Pages > Source`,並將 `Source` 改為 `GitHub Actions`。 @@ -24,7 +25,7 @@ name: Pages on: push: branches: - - main # default branch + - main # default branch jobs: build: @@ -40,7 +41,7 @@ jobs: with: # Examples: 20, 18.19, >=16.20.2, lts/Iron, lts/Hydrogen, *, latest, current, node # Ref: https://github.com/actions/setup-node#supported-version-syntax - node-version: '20' + node-version: "20" - name: Cache NPM dependencies uses: actions/cache@v4 with: @@ -94,13 +95,13 @@ jobs: 1. 安裝 [hexo-deployer-git](https://github.com/hexojs/hexo-deployer-git). 2. 清空 `_config.yml` 的現有資料,並新增以下組態: - ``` yml - deploy: - type: git - repo: https://github.com/<username>/<project> - # example, https://github.com/hexojs/hexojs.github.io - branch: gh-pages - ``` +```yml +deploy: + type: git + repo: https://github.com/<username>/<project> + # example, https://github.com/hexojs/hexojs.github.io + branch: gh-pages +``` 3. 執行 `hexo clean && hexo deploy` 。 4. 瀏覽 `<GitHub 用戶名>.github.io` 檢查你的網站能否運作。 diff --git a/source/zh-tw/docs/gitlab-pages.md b/source/zh-tw/docs/gitlab-pages.md index 392fc9f0e4..d0b6bf5408 100644 --- a/source/zh-tw/docs/gitlab-pages.md +++ b/source/zh-tw/docs/gitlab-pages.md @@ -7,7 +7,7 @@ title: 在 GitLab Pages 上部署 Hexo 3. 將 Hexo 檔案資料夾推播到資料庫中。預設情況下 `public/` 是不會被上載到資料庫,請確保 `.gitignore` 已經包含 `public/` 一行。你的 Hexo 資料庫大致上應該與[這裡](https://gitlab.com/pages/hexo)相同。 4. 於儲存庫目錄中新增 `.gitlab-ci.yml`: -``` yml +```yml image: node:10-alpine # use nodejs v10 LTS cache: paths: @@ -35,7 +35,7 @@ pages: 下文將講解如何在 GitLab 上設立專案頁面: 1. 前往 Hexo資料庫的 `Settings -> General -> Advanced -> Change path`。 更改成 `<GitLab 用戶名>.gitlab.io/<任何名稱>` (請將`<任何名稱>`替換成你會用到的名字) -2. 修改 **_config.yml**, 把 `root:` 的 `""` 改成 `"name"`. +2. 修改 **\_config.yml**, 把 `root:` 的 `""` 改成 `"name"`. 3. 確定並推播。 ## 參考鏈接 diff --git a/source/zh-tw/docs/helpers.md b/source/zh-tw/docs/helpers.md index d8f3263349..d8da09d506 100644 --- a/source/zh-tw/docs/helpers.md +++ b/source/zh-tw/docs/helpers.md @@ -1,6 +1,7 @@ --- title: 輔助函數(Helpers) --- + 輔助函數幫助您在模版中快速插入內容。 ## 網址 @@ -9,7 +10,7 @@ title: 輔助函數(Helpers) 在路徑前加上根路徑,從 Hexo 2.7 開始您應該使用此函數,避免使用 `config.root + path`。 -``` js +```js <%- url_for(path) %> ``` @@ -17,7 +18,7 @@ title: 輔助函數(Helpers) 取得與 `from` 相對的 `to` 路徑。 -``` js +```js <%- relative_url(from, to) %> ``` @@ -25,13 +26,13 @@ title: 輔助函數(Helpers) 插入 Gravatar 圖片。 -``` js +```js <%- gravatar(email, [size]) %> ``` **範例:** -``` js +```js <%- gravatar('a@abc.com') %> // https://www.gravatar.com/avatar/b9b00e66c6b8a70f88c73cb6bdb06787 @@ -48,13 +49,13 @@ title: 輔助函數(Helpers) 載入 CSS 檔案。`path` 可以是陣列或字串,如果 `path` 開頭不是 `/` 或任何協議,則會自動加上根路徑;如果後面沒有加上 `.css` 副檔名的話,也會自動加上。Use object type for custom attributes. -``` js +```js <%- css(path, ...) %> ``` **範例:** -``` js +```js <%- css('style.css') %> // <link rel="stylesheet" href="/style.css"> @@ -74,13 +75,13 @@ title: 輔助函數(Helpers) 載入 JavaScript 檔案。`path` 可以是陣列或字串,如果 `path` 開頭不是 `/` 或任何協議,則會自動加上根路徑;如果後面沒有加上 `.js` 副檔名的話,也會自動加上。Use object type for custom attributes. -``` js +```js <%- js(path, ...) %> ``` **範例:** -``` js +```js <%- js('script.js') %> // <script src="/script.js"></script> @@ -100,19 +101,19 @@ title: 輔助函數(Helpers) 插入連結。 -``` js +```js <%- link_to(path, [text], [options]) %> ``` -選項 | 描述 | 預設值 ---- | --- | --- -`external` | 在新視窗開啟連結 | false -`class` | Class 名稱 | -`id` | ID | +| 選項 | 描述 | 預設值 | +| ---------- | ---------------- | ------ | +| `external` | 在新視窗開啟連結 | false | +| `class` | Class 名稱 | +| `id` | ID | **範例:** -``` js +```js <%- link_to('http://www.google.com') %> // <a href="http://www.google.com" title="http://www.google.com">http://www.google.com</a> @@ -127,22 +128,22 @@ title: 輔助函數(Helpers) 插入電子郵件連結。 -``` js +```js <%- mail_to(path, [text], [options]) %> ``` -選項 | 描述 ---- | --- -`class` | Class 名稱 -`id` | ID -`subject` | 郵件主旨 -`cc` | 副本(CC) -`bcc` | 密件副本(BCC) -`body` | 郵件內容 +| 選項 | 描述 | +| --------- | --------------- | +| `class` | Class 名稱 | +| `id` | ID | +| `subject` | 郵件主旨 | +| `cc` | 副本(CC) | +| `bcc` | 密件副本(BCC) | +| `body` | 郵件內容 | **範例:** -``` js +```js <%- mail_to('a@abc.com') %> // <a href="mailto:a@abc.com" title="a@abc.com">a@abc.com</a> @@ -154,23 +155,23 @@ title: 輔助函數(Helpers) 插入圖片。 -``` js +```js <%- image_tag(path, [options]) %> ``` -選項 | 描述 ---- | --- -`alt` | 圖片的替代文字 -`class` | Class 名稱 -`id` | ID -`width` | 圖片寬度 -`height` | 圖片高度 +| 選項 | 描述 | +| -------- | -------------- | +| `alt` | 圖片的替代文字 | +| `class` | Class 名稱 | +| `id` | ID | +| `width` | 圖片寬度 | +| `height` | 圖片高度 | ### favicon_tag 插入 favicon。 -``` js +```js <%- favicon_tag(path) %> ``` @@ -178,18 +179,18 @@ title: 輔助函數(Helpers) 插入 feed 連結。 -``` js +```js <%- feed_tag(path, [options]) %> ``` -選項 | 描述 | 預設值 ---- | --- | --- -`title` | Feed 標題 | `config.title` -`type` | Feed 類型 | +| 選項 | 描述 | 預設值 | +| ------- | --------- | -------------- | +| `title` | Feed 標題 | `config.title` | +| `type` | Feed 類型 | **範例:** -``` js +```js <%- feed_tag('atom.xml') %> // <link rel="alternate" href="/atom.xml" title="Hexo" type="application/atom+xml"> @@ -207,7 +208,7 @@ title: 輔助函數(Helpers) 檢查 `path` 是否符合目前頁面的網址。開啟 `strict` 選項啟用嚴格比對。 -``` js +```js <%- is_current(path, [strict]) %> ``` @@ -215,7 +216,7 @@ title: 輔助函數(Helpers) 檢查目前是否為首頁。 -``` js +```js <%- is_home() %> ``` @@ -223,7 +224,7 @@ title: 輔助函數(Helpers) 檢查目前是否為文章。 -``` js +```js <%- is_post() %> ``` @@ -231,7 +232,7 @@ title: 輔助函數(Helpers) 檢查目前是否為彙整頁面。 -``` js +```js <%- is_archive() %> ``` @@ -239,7 +240,7 @@ title: 輔助函數(Helpers) 檢查目前是否為年度彙整頁面。 -``` js +```js <%- is_year() %> ``` @@ -247,7 +248,7 @@ title: 輔助函數(Helpers) 檢查目前是否為每月彙整頁面。 -``` js +```js <%- is_month() %> ``` @@ -255,7 +256,7 @@ title: 輔助函數(Helpers) 檢查目前是否為分類彙整頁面。 -``` js +```js <%- is_category() %> ``` @@ -263,7 +264,7 @@ title: 輔助函數(Helpers) 檢查目前是否為標籤彙整頁面。 -``` js +```js <%- is_tag() %> ``` @@ -273,7 +274,7 @@ title: 輔助函數(Helpers) 清除字串的開頭和結尾空白。 -``` js +```js <%- trim(string) %> ``` @@ -281,13 +282,13 @@ title: 輔助函數(Helpers) 清除字串中的 HTML 標籤。 -``` js +```js <%- strip_html(string) %> ``` **範例:** -``` js +```js <%- strip_html('It\'s not <b>important</b> anymore!') %> // It's not important anymore! ``` @@ -296,13 +297,13 @@ title: 輔助函數(Helpers) 把字串轉換為正確的 Title case。 -``` js +```js <%- titlecase(string) %> ``` **範例:** -``` js +```js <%- titlecase('this is an apple') %> # This is an Apple ``` @@ -311,13 +312,13 @@ title: 輔助函數(Helpers) 使用 Markdown 渲染字串。 -``` js +```js <%- markdown(str) %> ``` **範例:** -``` js +```js <%- markdown('make me **strong**') %> // make me <strong>strong</strong> ``` @@ -326,13 +327,13 @@ title: 輔助函數(Helpers) 渲染字串。 -``` js +```js <%- render(str, engine, [options]) %> ``` **Examples:** -``` js +```js <%- render('p(class="example") Test', 'pug'); %> // <p class="example">Test</p> ``` @@ -343,13 +344,13 @@ See [Rendering](https://hexo.io/zh-twapi/rendering) for more details. 使每行的字串長度不超過 `length`。`length` 預設為 80。 -``` js +```js <%- word_wrap(str, [length]) %> ``` **範例:** -``` js +```js <%- word_wrap('Once upon a time', 8) %> // Once upon\n a time ``` @@ -358,13 +359,13 @@ See [Rendering](https://hexo.io/zh-twapi/rendering) for more details. 移除超過 `length` 的字串。 -``` js +```js <%- truncate(text, length) %> ``` **範例:** -``` js +```js <%- truncate('Once upon a time in a world far far away', 16) %> // Once upon a time ``` @@ -373,13 +374,13 @@ See [Rendering](https://hexo.io/zh-twapi/rendering) for more details. Escapes HTML entities in a string. -``` js +```js <%- escape_html(str) %> ``` **Examples:** -``` js +```js <%- escape_html('<p>Hello "world".</p>') %> // <p>Hello "world".</p> ``` @@ -390,26 +391,26 @@ Escapes HTML entities in a string. 載入其他模板檔案,您可在 `locals` 設定區域變數。 -``` js +```js <%- partial(layout, [locals], [options]) %> ``` -選項 | 描述 | 預設值 ---- | --- | --- -`cache` | 儲存快取(使用 Fragment cache) | `false` -`only` | 限制區域變數。在模板中只能使用 `locals` 中設定的變數。 | `false` +| 選項 | 描述 | 預設值 | +| ------- | ------------------------------------------------------ | ------- | +| `cache` | 儲存快取(使用 Fragment cache) | `false` | +| `only` | 限制區域變數。在模板中只能使用 `locals` 中設定的變數。 | `false` | ### fragment_cache 儲存局部快取。它儲存局部內容,下次使用時就能直接使用快取。 -``` js +```js <%- fragment_cache(id, fn); ``` **範例:** -``` js +```js <%- fragment_cache('header', function(){ return '<header></header>'; }) %> @@ -421,13 +422,13 @@ Escapes HTML entities in a string. 插入格式化的日期。`date` 可以是 UNIX 時間、ISO 字串、Date 物件或 [Moment.js] 物件。`format` 預設為 `date_format` 設定。 -``` js +```js <%- date(date, [format]) %> ``` **範例:** -``` js +```js <%- date(Date.now()) %> // 2013-01-01 @@ -439,13 +440,13 @@ Escapes HTML entities in a string. 插入 XML 格式的日期。`date` 可以是 UNIX 時間、ISO 字串、Date 物件或 [Moment.js] 物件。 -``` js +```js <%- date_xml(date) %> ``` **範例:** -``` js +```js <%- date_xml(Date.now()) %> // 2013-01-01T00:00:00.000Z ``` @@ -454,13 +455,13 @@ Escapes HTML entities in a string. 插入格式化的時間。`date` 可以是 UNIX 時間、ISO 字串、Date 物件或 [Moment.js] 物件。`format` 預設為 `time_format` 設定。 -``` js +```js <%- time(date, [format]) %> ``` **範例:** -``` js +```js <%- time(Date.now()) %> // 13:05:12 @@ -472,13 +473,13 @@ Escapes HTML entities in a string. 插入格式化的日期和時間。`date` 可以是 UNIX 時間、ISO 字串、Date 物件或 [Moment.js] 物件。`format` 預設為 `date_format + time_format` 設定。 -``` js +```js <%- full_date(date, [format]) %> ``` **範例:** -``` js +```js <%- full_date(new Date()) %> // Jan 1, 2013 0:00:00 @@ -496,7 +497,7 @@ Inserts relative time from now. `date` can be unix time, ISO string, date object **Examples:** -``` js +```js <%- relative_date(new Date()) %> // a few seconds ago @@ -514,7 +515,7 @@ Inserts time tag. `date` can be unix time, ISO string, date object, or [Moment.j **Examples:** -``` js +```js <%- time_tag(new Date()) %> // <time datetime="2024-01-22T06:35:31.108Z">2024-01-22</time> @@ -532,50 +533,50 @@ Inserts time tag. `date` can be unix time, ISO string, date object, or [Moment.j 插入分類列表。 -``` js +```js <%- list_categories([categories], [options]) %> ``` -選項 | 描述 | 預設值 ---- | --- | --- -`orderby` | 分類排列方式 | name -`order` | 分類排列順序。`1`, `asc` 升冪;`-1`, `desc` 降冪。 | 1 -`show_count` | 顯示每個分類的文章總數 | true -`style` | 分類列表的顯示方式。使用 `list` 以無序列表(unordered list)方式顯示。 | list -`separator` | 分類間的分隔符號。只有在 `style` 不是 `list` 時有用。 | , -`depth` | 要顯示的分類層級。`0` 顯示所有層級的分類;`-1` 和 `0` 很類似,但是顯示不分層級;`1` 只顯示第一層的分類。 | 0 -`class` | 分類列表的 class 名稱。 | category -`transform` | 改變分類名稱顯示方法的函數 | +| 選項 | 描述 | 預設值 | +| ------------ | -------------------------------------------------------------------------------------------------------- | -------- | +| `orderby` | 分類排列方式 | name | +| `order` | 分類排列順序。`1`, `asc` 升冪;`-1`, `desc` 降冪。 | 1 | +| `show_count` | 顯示每個分類的文章總數 | true | +| `style` | 分類列表的顯示方式。使用 `list` 以無序列表(unordered list)方式顯示。 | list | +| `separator` | 分類間的分隔符號。只有在 `style` 不是 `list` 時有用。 | , | +| `depth` | 要顯示的分類層級。`0` 顯示所有層級的分類;`-1` 和 `0` 很類似,但是顯示不分層級;`1` 只顯示第一層的分類。 | 0 | +| `class` | 分類列表的 class 名稱。 | category | +| `transform` | 改變分類名稱顯示方法的函數 | ### list_tags 插入標籤列表。 -``` js +```js <%- list_tags([tags], [options]) %> ``` -選項 | 描述 | 預設值 ---- | --- | --- -`orderby` | 標籤排列方式 | name -`order` | 標籤排列順序。`1`, `asc` 升冪;`-1`, `desc` 降冪。 | 1 -`show_count` | 顯示每個標籤的文章總數 | true -`style` | 標籤列表的顯示方式。使用 `list` 以無序列表(unordered list)方式顯示。 | list -`separator` | 標籤間的分隔符號。只有在 `style` 不是 `list` 時有用。 | , -`class` | Class name of tag list (string) or customize each tag's class (object, see below). | tag -`transform` | 改變標籤名稱顯示方法的函數 | -`amount` | 要顯示的標籤數量(0 = 無限制) | 0 -`suffix` | Add a suffix to link. | None +| 選項 | 描述 | 預設值 | +| ------------ | ---------------------------------------------------------------------------------- | ------ | +| `orderby` | 標籤排列方式 | name | +| `order` | 標籤排列順序。`1`, `asc` 升冪;`-1`, `desc` 降冪。 | 1 | +| `show_count` | 顯示每個標籤的文章總數 | true | +| `style` | 標籤列表的顯示方式。使用 `list` 以無序列表(unordered list)方式顯示。 | list | +| `separator` | 標籤間的分隔符號。只有在 `style` 不是 `list` 時有用。 | , | +| `class` | Class name of tag list (string) or customize each tag's class (object, see below). | tag | +| `transform` | 改變標籤名稱顯示方法的函數 | +| `amount` | 要顯示的標籤數量(0 = 無限制) | 0 | +| `suffix` | Add a suffix to link. | None | Class advanced customization: -Option | Description | Default ---- | --- | --- -`class.ul` | `<ul>` class name (only for style `list`) | `tag-list` (list style) -`class.li` | `<li>` class name (only for style `list`) | `tag-list-item` (list style) -`class.a` | `<a>` class name | `tag-list-link` (list style) `tag-link` (normal style) -`class.label` | `<span>` class name where the tag label is stored (only for normal style, when `class.label` is set the label is put in a `<span>`) | `tag-label` (normal style) -`class.count` | `<span>` class name where the tag counter is stored (only when `show_count` is `true`) | `tag-list-count` (list style) `tag-count` (normal style) +| Option | Description | Default | +| ------------- | ----------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------- | +| `class.ul` | `<ul>` class name (only for style `list`) | `tag-list` (list style) | +| `class.li` | `<li>` class name (only for style `list`) | `tag-list-item` (list style) | +| `class.a` | `<a>` class name | `tag-list-link` (list style) `tag-link` (normal style) | +| `class.label` | `<span>` class name where the tag label is stored (only for normal style, when `class.label` is set the label is put in a `<span>`) | `tag-label` (normal style) | +| `class.count` | `<span>` class name where the tag counter is stored (only when `show_count` is `true`) | `tag-list-count` (list style) `tag-count` (normal style) | Examples: @@ -590,60 +591,60 @@ Examples: 插入彙整列表。 -``` js +```js <%- list_archives([options]) %> ``` -選項 | 描述 | 預設值 ---- | --- | --- -`type` | 類型。此設定可為 `yearly` 或 `monthly`。 | monthly -`order` | 排列順序。`1`, `asc` 升冪;`-1`, `desc` 降冪。 | 1 -`show_count` | 顯示每個彙整的文章總數 | true -`format` | 日期格式 | MMMM YYYY -`style` | 彙整列表的顯示方式。使用 `list` 以無序列表(unordered list)方式顯示。 | list -`separator` | 彙整間的分隔符號。只有在 `style` 不是 `list` 時有用。 | , -`class` | 彙整列表的 class 名稱。 | archive -`transform` | 改變彙整名稱顯示方法的函數 | +| 選項 | 描述 | 預設值 | +| ------------ | ---------------------------------------------------------------------- | --------- | +| `type` | 類型。此設定可為 `yearly` 或 `monthly`。 | monthly | +| `order` | 排列順序。`1`, `asc` 升冪;`-1`, `desc` 降冪。 | 1 | +| `show_count` | 顯示每個彙整的文章總數 | true | +| `format` | 日期格式 | MMMM YYYY | +| `style` | 彙整列表的顯示方式。使用 `list` 以無序列表(unordered list)方式顯示。 | list | +| `separator` | 彙整間的分隔符號。只有在 `style` 不是 `list` 時有用。 | , | +| `class` | 彙整列表的 class 名稱。 | archive | +| `transform` | 改變彙整名稱顯示方法的函數 | ### list_posts 插入文章列表。 -``` js +```js <%- list_posts([options]) %> ``` -選項 | 描述 | 預設值 ---- | --- | --- -`orderby` | 文章排列方式 | date -`order` | 文章排列順序。`1`, `asc` 升冪;`-1`, `desc` 降冪。 | -1 -`style` | 文章列表的顯示方式。使用 `list` 以無序列表(unordered list)方式顯示。 | list -`separator` | 文章間的分隔符號。只有在 `style` 不是 `list` 時有用。 | , -`class` | 文章列表的 class 名稱。 | post -`amount` | 要顯示的文章數量(0 = 無限制) | 6 -`transform` | 改變文章名稱顯示方法的函數 | +| 選項 | 描述 | 預設值 | +| ----------- | ---------------------------------------------------------------------- | ------ | +| `orderby` | 文章排列方式 | date | +| `order` | 文章排列順序。`1`, `asc` 升冪;`-1`, `desc` 降冪。 | -1 | +| `style` | 文章列表的顯示方式。使用 `list` 以無序列表(unordered list)方式顯示。 | list | +| `separator` | 文章間的分隔符號。只有在 `style` 不是 `list` 時有用。 | , | +| `class` | 文章列表的 class 名稱。 | post | +| `amount` | 要顯示的文章數量(0 = 無限制) | 6 | +| `transform` | 改變文章名稱顯示方法的函數 | ### tagcloud 插入標籤雲。 -``` js +```js <%- tagcloud([tags], [options]) %> ``` -選項 | 描述 | 預設值 ---- | --- | --- -`min_font` | 最小字體尺寸 | 10 -`max_font` | 最大字體尺寸 | 20 -`unit` | 字體尺寸的單位 | px -`amount` | 標籤總量 | 40 -`orderby` | 標籤排列方式 | name -`order` | 標籤排列順序。`1`, `sac` 升冪;`-1`, `desc` 降冪 | 1 -`color` | 使用顏色 | false -`start_color` | 開始的顏色。您可使用十六進位值(`#b700ff`),rgba(`rgba(183, 0, 255, 1)`),hsla(`hsla(283, 100%, 50%, 1)`)或 [顏色關鍵字]。此選項僅在 `color` 設定開啟時才有用。 | -`end_color` | 結束的顏色。您可使用十六進位值(`#b700ff`),rgba(`rgba(183, 0, 255, 1)`),hsla(`hsla(283, 100%, 50%, 1)`)或 [顏色關鍵字]。此選項僅在 `color` 設定開啟時才有用。 | -`class` | 標籤的 class name prefix of tags -`level` | 不同 class name 的總數。此選項僅在 `class` 設定時才有用。 | 10 +| 選項 | 描述 | 預設值 | +| ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------ | +| `min_font` | 最小字體尺寸 | 10 | +| `max_font` | 最大字體尺寸 | 20 | +| `unit` | 字體尺寸的單位 | px | +| `amount` | 標籤總量 | 40 | +| `orderby` | 標籤排列方式 | name | +| `order` | 標籤排列順序。`1`, `sac` 升冪;`-1`, `desc` 降冪 | 1 | +| `color` | 使用顏色 | false | +| `start_color` | 開始的顏色。您可使用十六進位值(`#b700ff`),rgba(`rgba(183, 0, 255, 1)`),hsla(`hsla(283, 100%, 50%, 1)`)或 [顏色關鍵字]。此選項僅在 `color` 設定開啟時才有用。 | +| `end_color` | 結束的顏色。您可使用十六進位值(`#b700ff`),rgba(`rgba(183, 0, 255, 1)`),hsla(`hsla(283, 100%, 50%, 1)`)或 [顏色關鍵字]。此選項僅在 `color` 設定開啟時才有用。 | +| `class` | 標籤的 class name prefix of tags | +| `level` | 不同 class name 的總數。此選項僅在 `class` 設定時才有用。 | 10 | ## 其他 @@ -651,35 +652,35 @@ Examples: 插入分頁連結。 -``` js +```js <%- paginator(options) %> ``` -選項 | 描述 | 預設值 ---- | --- | --- -`base` | 基礎網址 | / -`format` | 網址格式 | page/%d/ -`total` | 分頁總數 | 1 -`current` | 目前頁數 | 0 -`prev_text` | 上一頁連結的文字。僅在 `prev_next` 設定開啟時才有用。 | Prev -`next_text` | 下一頁連結的文字。僅在 `prev_next` 設定開啟時才有用。 | Next -`space` | 空白文字 | &hellp; -`prev_next` | 顯示上一頁和下一頁的連結 | true -`end_size` | 顯示於兩側的頁數 | 1 -`mid_size` | 顯示於中間的頁數 | 2 -`show_all` | 顯示所有頁數。如果開啟此設定的話,`end_size` 和 `mid_size` 就沒用了。 | false -`escape` | Escape HTML tags | true +| 選項 | 描述 | 預設值 | +| ----------- | --------------------------------------------------------------------- | -------- | +| `base` | 基礎網址 | / | +| `format` | 網址格式 | page/%d/ | +| `total` | 分頁總數 | 1 | +| `current` | 目前頁數 | 0 | +| `prev_text` | 上一頁連結的文字。僅在 `prev_next` 設定開啟時才有用。 | Prev | +| `next_text` | 下一頁連結的文字。僅在 `prev_next` 設定開啟時才有用。 | Next | +| `space` | 空白文字 | &hellp; | +| `prev_next` | 顯示上一頁和下一頁的連結 | true | +| `end_size` | 顯示於兩側的頁數 | 1 | +| `mid_size` | 顯示於中間的頁數 | 2 | +| `show_all` | 顯示所有頁數。如果開啟此設定的話,`end_size` 和 `mid_size` 就沒用了。 | false | +| `escape` | Escape HTML tags | true | **Examples:** -``` js +```js <%- paginator({ prev_text: '<', next_text: '>' }) %> ``` -``` html +```html <!-- Rendered as --> <a href="/1/"><</a> <a href="/1/">1</a> @@ -688,7 +689,7 @@ Examples: <a href="/3/">></a> ``` -``` js +```js <%- paginator({ prev_text: '<i class="fa fa-angle-left"></i>', next_text: '<i class="fa fa-angle-right"></i>', @@ -696,7 +697,7 @@ Examples: }) %> ``` -``` html +```html <!-- Rendered as --> <a href="/1/"><i class="fa fa-angle-left"></i></a> <a href="/1/">1</a> @@ -709,33 +710,33 @@ Examples: 插入 Google 搜尋表單。 -``` js +```js <%- search_form(options) %> ``` -選項 | 描述 | 預設值 ---- | --- | --- -`class` | 表單的 class name | search-form -`text` | 搜尋提示文字 | Search -`button` | 顯示搜尋按鈕。此設定可為布林值(boolean)或字串,當設定是字串的時候,即為搜尋按鈕的文字。 | false +| 選項 | 描述 | 預設值 | +| -------- | ----------------------------------------------------------------------------------------- | ----------- | +| `class` | 表單的 class name | search-form | +| `text` | 搜尋提示文字 | Search | +| `button` | 顯示搜尋按鈕。此設定可為布林值(boolean)或字串,當設定是字串的時候,即為搜尋按鈕的文字。 | false | ### number_format 格式化數字。 -``` js +```js <%- number_format(number, [options]) %> ``` -選項 | 描述 | 預設值 ---- | --- | --- -`precision` | 數字精確度。此選項可為 `false` 或非負整數。 | false -`delimiter` | 千位數分隔符號 | , -`separator` | 整數和小數之間的分隔符號 | . +| 選項 | 描述 | 預設值 | +| ----------- | ------------------------------------------- | ------ | +| `precision` | 數字精確度。此選項可為 `false` 或非負整數。 | false | +| `delimiter` | 千位數分隔符號 | , | +| `separator` | 整數和小數之間的分隔符號 | . | **範例:** -``` js +```js <%- number_format(12345.67, {precision: 1}) %> // 12,345.68 @@ -756,13 +757,13 @@ Examples: Inserts [generator tag](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta). -``` js +```js <%- meta_generator() %> ``` **Examples:** -``` js +```js <%- meta_generator() %> // <meta name="generator" content="Hexo 4.0.0"> ``` @@ -771,48 +772,48 @@ Inserts [generator tag](https://developer.mozilla.org/en-US/docs/Web/HTML/Elemen 插入 [Open Graph] 資料。 -``` js +```js <%- open_graph([options]) %> ``` -選項 | 描述 | 預設值 ---- | --- | --- -`title` | 頁面標題 (`og:title`) | `page.title` -`type` | 頁面類型 (`og:type`) | article(post page)<br>website(non-post page) -`url` | 頁面網址 (`og:url`) | `url` -`image` | 頁面圖片 (`og:image`) | 內容中的圖片 -`author` | Article author (`og:article:author`) | `config.author` -`date` | Article published time (`og:article:published_time`) | Page published time -`updated` | Article modified time (`og:article:modified_time`) | Page modified time -`language` | Article language (`og:locale`) | `page.lang \|\| page.language \|\| config.language` -`site_name` | 網站名稱 (`og:site_name`) | `config.title` -`description` | 頁面描述 (`og:description`) | 內容摘要或前 200 字 -`twitter_card` | Twitter 卡片類型 (`twitter:card`) | summary -`twitter_id` | Twitter ID (`twitter:creator`) | -`twitter_site` | Twitter 網站 (`twitter:site`) | -`twitter_image` | Twitter 圖片 (`twitter:image`) | -`google_plus` | Google+ 個人資料連結 | -`fb_admins` | Facebook 管理者 ID | -`fb_app_id` | Facebook 應用程式 ID | +| 選項 | 描述 | 預設值 | +| --------------- | ---------------------------------------------------- | --------------------------------------------------- | +| `title` | 頁面標題 (`og:title`) | `page.title` | +| `type` | 頁面類型 (`og:type`) | article(post page)<br>website(non-post page) | +| `url` | 頁面網址 (`og:url`) | `url` | +| `image` | 頁面圖片 (`og:image`) | 內容中的圖片 | +| `author` | Article author (`og:article:author`) | `config.author` | +| `date` | Article published time (`og:article:published_time`) | Page published time | +| `updated` | Article modified time (`og:article:modified_time`) | Page modified time | +| `language` | Article language (`og:locale`) | `page.lang \|\| page.language \|\| config.language` | +| `site_name` | 網站名稱 (`og:site_name`) | `config.title` | +| `description` | 頁面描述 (`og:description`) | 內容摘要或前 200 字 | +| `twitter_card` | Twitter 卡片類型 (`twitter:card`) | summary | +| `twitter_id` | Twitter ID (`twitter:creator`) | +| `twitter_site` | Twitter 網站 (`twitter:site`) | +| `twitter_image` | Twitter 圖片 (`twitter:image`) | +| `google_plus` | Google+ 個人資料連結 | +| `fb_admins` | Facebook 管理者 ID | +| `fb_app_id` | Facebook 應用程式 ID | ### toc 解析內容中的標題標籤 (h1~h6) 並插入目錄。 -``` js +```js <%- toc(str, [options]) %> ``` -選項 | 描述 | 預設值 ---- | --- | --- -`class` | Class 名稱 | toc -`list_number` | 顯示編號 | true -`max_depth` | 生成 TOC 的最大深度 | 6 -`min_depth` | 生成 TOC 的最小深度 | 1 +| 選項 | 描述 | 預設值 | +| ------------- | ------------------- | ------ | +| `class` | Class 名稱 | toc | +| `list_number` | 顯示編號 | true | +| `max_depth` | 生成 TOC 的最大深度 | 6 | +| `min_depth` | 生成 TOC 的最小深度 | 1 | **範例:** -``` js +```js <%- toc(page.content) %> ``` @@ -828,7 +829,7 @@ Please see below PRs. - https://github.com/hexojs/hexo/pull/4871 - https://github.com/hexojs/hexo-util/pull/269 - https://github.com/hexojs/hexo-renderer-markdown-it/pull/174 -{% endnote %} + {% endnote %} [顏色關鍵字]: http://www.w3.org/TR/css3-color/#svg-color [Moment.js]: http://momentjs.com/ diff --git a/source/zh-tw/docs/index.md b/source/zh-tw/docs/index.md index bbe605ccb4..27d0582a6b 100644 --- a/source/zh-tw/docs/index.md +++ b/source/zh-tw/docs/index.md @@ -1,6 +1,7 @@ --- title: 文件 --- + 歡迎使用 Hexo,此文件將幫助您快速開始使用。如果您在使用途中遇到任何問題,您可以在 [解決問題](troubleshooting.html) 中找到解答,或者也可以在 [GitHub](https://github.com/hexojs/hexo/issues) 或 [Google Group](https://groups.google.com/group/hexo) 上詢問。 {% youtube PsXWbI2Mqu0 %} @@ -22,7 +23,7 @@ Hexo 是一個快速、簡單且強大的網誌框架。Hexo 使用 [Markdown](h 若您的電腦已經安裝上述的必備軟體,那麼恭喜您!只需要透過 npm 即可完成 Hexo 的安裝。 -``` bash +```bash $ npm install -g hexo-cli ``` @@ -57,7 +58,7 @@ Node.js 為大多數平台提供了官方的 [安裝程序](https://nodejs.org/e {% endnote %} {% note warn For Mac / Linux 用戶 %} -如果在嘗試安裝Hexo 的過程中出現`EACCES` 權限錯誤,請遵循[由npmjs 發布的指導](https://docs.npmjs.com/resolving-eacces-permissions-errors-when-installing-packages-globally ) 修復該問題。強烈建議 **不要** 使用 root、sudo 等方法覆蓋權限 +如果在嘗試安裝Hexo 的過程中出現`EACCES` 權限錯誤,請遵循[由npmjs 發布的指導](https://docs.npmjs.com/resolving-eacces-permissions-errors-when-installing-packages-globally) 修復該問題。強烈建議 **不要** 使用 root、sudo 等方法覆蓋權限 {% endnote %} {% note info Linux 用戶 %} @@ -68,7 +69,7 @@ Node.js 為大多數平台提供了官方的 [安裝程序](https://nodejs.org/e 一旦所有的必備軟體都安裝完畢後,即可透過 npm 安裝 Hexo: -``` bash +```bash $ npm install -g hexo-cli ``` @@ -76,19 +77,19 @@ $ npm install -g hexo-cli 如果您堅持使用較舊版本的 Node.js,你可以考慮安裝過往版本的 Hexo。 -請注意我們並不會對於過往版本的 Hexo 進行錯誤修復。 +請注意我們並不會對於過往版本的 Hexo 進行錯誤修復。 有可能的話,我們強烈建議總是安裝[最新版本](https://www.npmjs.com/package/hexo?activeTab=versions)的 Hexo 以及[推薦版本](#安裝需求)的 Node.js。 -Hexo 版本 | 最小可行 (Node.js 版本) | 小於 (Node.js 版本) ---- | --- | --- -7.0+ | 14.0.0 | latest -6.2+ | 12.13.0 | latest -6.0+ | 12.13.0 | 18.5.0 -5.0+ | 10.13.0 | 12.0.0 -4.1 - 4.2 | 8.10 | 10.0.0 -4.0 | 8.6 | 8.10.0 -3.3 - 3.9 | 6.9 | 8.0.0 -3.2 - 3.3 | 0.12 | unknown -3.0 - 3.1 | 0.10 or iojs | unknown -0.0.1 - 2.8 | 0.10 | unknown +| Hexo 版本 | 最小可行 (Node.js 版本) | 小於 (Node.js 版本) | +| ----------- | ----------------------- | ------------------- | +| 7.0+ | 14.0.0 | latest | +| 6.2+ | 12.13.0 | latest | +| 6.0+ | 12.13.0 | 18.5.0 | +| 5.0+ | 10.13.0 | 12.0.0 | +| 4.1 - 4.2 | 8.10 | 10.0.0 | +| 4.0 | 8.6 | 8.10.0 | +| 3.3 - 3.9 | 6.9 | 8.0.0 | +| 3.2 - 3.3 | 0.12 | unknown | +| 3.0 - 3.1 | 0.10 or iojs | unknown | +| 0.0.1 - 2.8 | 0.10 | unknown | diff --git a/source/zh-tw/docs/internationalization.md b/source/zh-tw/docs/internationalization.md index d3122d8e14..eeac1fdd33 100644 --- a/source/zh-tw/docs/internationalization.md +++ b/source/zh-tw/docs/internationalization.md @@ -1,12 +1,13 @@ --- title: 國際化(i18n) --- + 若要讓您的網站以不同語言呈現,您可使用國際化(internationalization)功能。請先在 `_config.yml` 中調整 `language` 設定,這代表的是預設語言,您也可設定多個語言來調整預設語言的順位。 -``` yaml +```yaml language: zh-tw -language: +language: - zh-tw - en ``` @@ -19,7 +20,7 @@ language: 在模板中,透過 `__` 或 `_p` 輔助函數,即可取得翻譯後的字串,前者用於一般使用;而後者用於複數字串。例如: -``` yaml en.yml +```yaml en.yml index: title: Home add: Add @@ -29,7 +30,7 @@ index: other: %d videos ``` -``` js +```js <%= __('index.title') %> // Home @@ -41,13 +42,13 @@ index: 您可在 front-matter 中指定該頁面的語言,也可在 `_config.yml` 中修改 `i18n_dir` 設定,讓 Hexo 自動偵測。 -``` yaml +```yaml i18n_dir: :lang ``` `i18n_dir` 的預設值是 `:lang`,也就是說 Hexo 會擷取網址中的第一段以偵測語言,舉例來說: -``` plain +```plain /index.html => en /archives/index.html => en /zh-tw/index.html => zh-tw diff --git a/source/zh-tw/docs/migration.md b/source/zh-tw/docs/migration.md index 028f14a181..8bac624201 100644 --- a/source/zh-tw/docs/migration.md +++ b/source/zh-tw/docs/migration.md @@ -1,17 +1,18 @@ --- title: 轉移 --- + ## RSS 首先,安裝 `hexo-migrator-rss` 外掛。 -``` bash +```bash $ npm install hexo-migrator-rss --save ``` 一旦外掛安裝完成,執行下列指令,從 RSS 轉移所有文章。`source` 可以是檔案路徑或網址。 -``` bash +```bash $ hexo migrate rss <source> ``` @@ -19,7 +20,7 @@ $ hexo migrate rss <source> 把 `_posts` 資料夾內的所有檔案複製至 `source/_posts` 資料夾,並在 `_config.yml` 中修改 `new_post_name` 設定。 -``` yaml +```yaml new_post_name: :year-:month-:day-:title.md ``` @@ -27,7 +28,7 @@ new_post_name: :year-:month-:day-:title.md 把 Octopress 的 `source/_posts` 資料夾內的所有檔案轉移至 Hexo 的 `source/_posts` 資料夾,並修改 `_config.yml` 中的 `new_post_name` 設定。 -``` yaml +```yaml new_post_name: :year-:month-:day-:title.md ``` @@ -35,7 +36,7 @@ new_post_name: :year-:month-:day-:title.md 首先,安裝 `hexo-migrator-wordpress` 外掛。 -``` bash +```bash $ npm install hexo-migrator-wordpress --save ``` @@ -43,7 +44,7 @@ $ npm install hexo-migrator-wordpress --save 接著執行: -``` bash +```bash $ hexo migrate wordpress <source> ``` diff --git a/source/zh-tw/docs/one-command-deployment.md b/source/zh-tw/docs/one-command-deployment.md index 56db524367..5d4c22c822 100644 --- a/source/zh-tw/docs/one-command-deployment.md +++ b/source/zh-tw/docs/one-command-deployment.md @@ -6,25 +6,25 @@ title: 佈署 Hexo 提供了快速方便的一鍵佈署功能,讓您只需一個指令就能將網站佈署到伺服器上。 -``` bash +```bash $ hexo deploy ``` 在開始之前,您必須先在 `_config.yml` 中修改設定,一個正確的部署設定中至少要有 `type` 欄位,例如: -``` yaml +```yaml deploy: type: git ``` 您可同時使用多個佈署器 (deployer),Hexo 會依照順序執行每個佈署器。 -``` yaml +```yaml deploy: -- type: git - repo: -- type: heroku - repo: + - type: git + repo: + - type: heroku + repo: ``` 更多佈署外掛,請參照[外掛](https://hexo.io/plugins/)清單。 @@ -33,13 +33,13 @@ deploy: 1. 安裝 [hexo-deployer-git]。 -``` bash +```bash $ npm install hexo-deployer-git --save ``` -2. 修改_config.yml設定(下面的註解顯示了參數的範例)。 +2. 修改\_config.yml設定(下面的註解顯示了參數的範例)。 -``` yaml +```yaml deploy: type: git repo: <repository url> #https://bitbucket.org/JohnSmith/johnsmith.bitbucket.io @@ -47,53 +47,53 @@ deploy: message: [message] ``` -選項 | 描述 | 預設 ---- | --- | --- -`repo` | 儲存庫(Repository)網址 | -`branch` | 分支名稱。| `gh-pages` (GitHub)<br>`coding-pages` (Coding.net)<br>`master` (其他) -`message` | 自訂提交訊息 | `Site updated: {% raw %}{{ now('YYYY-MM-DD HH:mm:ss') }}{% endraw %}`) -`token` | 選填的 token 值用來儲存庫存取身份認證。以 `$` 作為前綴從環境變數中讀取 token +| 選項 | 描述 | 預設 | +| --------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------- | +| `repo` | 儲存庫(Repository)網址 | +| `branch` | 分支名稱。 | `gh-pages` (GitHub)<br>`coding-pages` (Coding.net)<br>`master` (其他) | +| `message` | 自訂提交訊息 | `Site updated: {% raw %}{{ now('YYYY-MM-DD HH:mm:ss') }}{% endraw %}`) | +| `token` | 選填的 token 值用來儲存庫存取身份認證。以 `$` 作為前綴從環境變數中讀取 token | 3. 上傳你的網站。執行 `hexo clean && hexo deploy`。 - - 你將會被提示提供目標儲存庫的使用者名稱及密碼,除非你用 token 或是 ssh 金鑰進行身份驗證。 - - hexo-deployer-git 不會儲存你的使用者名稱及密碼。使用 [git-credential-cache](https://git-scm.com/docs/git-credential-cache) 來暫時儲存它們。 +- 你將會被提示提供目標儲存庫的使用者名稱及密碼,除非你用 token 或是 ssh 金鑰進行身份驗證。 +- hexo-deployer-git 不會儲存你的使用者名稱及密碼。使用 [git-credential-cache](https://git-scm.com/docs/git-credential-cache) 來暫時儲存它們。 -4. 在 Github / BitBucket / Gitlab 前往你的儲存庫設定,並將你的主要分支從 `master` 設為 `gh-pages`(或者任何你在 _config.yml 中設定的名字)。現在你的網站就是你的帳號首頁。 +4. 在 Github / BitBucket / Gitlab 前往你的儲存庫設定,並將你的主要分支從 `master` 設為 `gh-pages`(或者任何你在 \_config.yml 中設定的名字)。現在你的網站就是你的帳號首頁。 ## Heroku 安裝 [hexo-deployer-heroku]。 -``` bash +```bash $ npm install hexo-deployer-heroku --save ``` 修改設定。 -``` yaml +```yaml deploy: type: heroku repo: <repository url> message: [message] ``` -選項 | 描述 ---- | --- -`repo` | Heroku 儲存庫網址 -`message` | 自訂提交訊息 (預設是 `Site updated: {% raw %}{{ now('YYYY-MM-DD HH:mm:ss') }}{% endraw %}`) +| 選項 | 描述 | +| --------- | ------------------------------------------------------------------------------------------- | +| `repo` | Heroku 儲存庫網址 | +| `message` | 自訂提交訊息 (預設是 `Site updated: {% raw %}{{ now('YYYY-MM-DD HH:mm:ss') }}{% endraw %}`) | ## Rsync 安裝 [hexo-deployer-rsync]。 -``` bash +```bash $ npm install hexo-deployer-rsync --save ``` 修改設定。 -``` yaml +```yaml deploy: type: rsync host: <host> @@ -105,15 +105,15 @@ deploy: ignore_errors: [true|false] ``` -選項 | 描述 | 預設值 ---- | --- | --- -`host` | 遠端主機的位址 | -`user` | 使用者名稱 | -`root` | 遠端主機的根目錄 | -`port` | 連接埠 | 22 -`delete` | 刪除遠端主機上的舊檔案 | true -`verbose` | 顯示除錯訊息 | true -`ignore_errors` | 忽略錯誤 | false +| 選項 | 描述 | 預設值 | +| --------------- | ---------------------- | ------ | +| `host` | 遠端主機的位址 | +| `user` | 使用者名稱 | +| `root` | 遠端主機的根目錄 | +| `port` | 連接埠 | 22 | +| `delete` | 刪除遠端主機上的舊檔案 | true | +| `verbose` | 顯示除錯訊息 | true | +| `ignore_errors` | 忽略錯誤 | false | ## OpenShift @@ -123,35 +123,35 @@ deploy: 安裝 [hexo-deployer-openshift]。 -``` bash +```bash $ npm install hexo-deployer-openshift --save ``` 修改設定。 -``` yaml +```yaml deploy: type: openshift repo: <repository url> message: [message] ``` -選項 | 描述 ---- | --- -`repo` | OpenShift 儲存庫網址 -`message` | 自訂提交訊息 (預設是 `Site updated: {% raw %}{{ now('YYYY-MM-DD HH:mm:ss') }}{% endraw %}`) +| 選項 | 描述 | +| --------- | ------------------------------------------------------------------------------------------- | +| `repo` | OpenShift 儲存庫網址 | +| `message` | 自訂提交訊息 (預設是 `Site updated: {% raw %}{{ now('YYYY-MM-DD HH:mm:ss') }}{% endraw %}`) | ## FTPSync 安裝 [hexo-deployer-ftpsync]。 -``` bash +```bash $ npm install hexo-deployer-ftpsync --save ``` 修改設定。 -``` yaml +```yaml deploy: type: ftpsync host: <host> @@ -163,15 +163,15 @@ deploy: verbose: [true|false] ``` -選項 | 描述 | 預設值 ---- | --- | --- -`host` | 遠端主機位址 | -`user` | 使用者名稱 | -`pass` | 密碼 | -`remote` | 遠端主機的根目錄 | `/` -`port` | 連接埠 | 21 -`clear` | 在上傳之前,移除遠端目錄中所有檔案及目錄 | false -`verbose` | 顯示除錯訊息 | false +| 選項 | 描述 | 預設值 | +| --------- | ---------------------------------------- | ------ | +| `host` | 遠端主機位址 | +| `user` | 使用者名稱 | +| `pass` | 密碼 | +| `remote` | 遠端主機的根目錄 | `/` | +| `port` | 連接埠 | 21 | +| `clear` | 在上傳之前,移除遠端目錄中所有檔案及目錄 | false | +| `verbose` | 顯示除錯訊息 | false | ## Vercel @@ -233,8 +233,8 @@ After a few moments, your website will be deployed. 2. 修改配置。 - ``` yaml - deploy: # 所有部署器的根配置塊 +```yaml +deploy: # 所有部署器的根配置塊 - type: rss3 endpoint: https://hub.rss3.io privateKey: 47e18d6c386898b424025cd9db446f779ef24ad33a26c499c87bb3d9372540ba @@ -244,14 +244,14 @@ After a few moments, your website will be deployed. api: key: d693df715d3631e489d6 secret: ee8b74626f12b61c1a4bde3b8c331ad390567c86ba779c9b18561ee92c1cbff0 - ``` +``` -| 參數 | 描述 | -| ----------------- | ---------------------- | +| 參數 | 描述 | +| ----------------- | ----------------------- | | `endpoint` | 一個 RSS3 Hub 的鏈接 | | `privateKey` | 您的私鑰, 64 字節 | | `ipfs/deploy` | 是否部署到 IPFS 上 | -| `ipfs/gateway` | IPFS API 網關 | +| `ipfs/gateway` | IPFS API 網關 | | `ipfs/api/key` | IPFS 網關相關的驗證內容 | | `ipfs/api/secret` | IPFS 網關相關的驗證內容 | diff --git a/source/zh-tw/docs/permalinks.md b/source/zh-tw/docs/permalinks.md index 493948f884..c04fba78a6 100644 --- a/source/zh-tw/docs/permalinks.md +++ b/source/zh-tw/docs/permalinks.md @@ -1,84 +1,85 @@ --- title: 永久連結(Permalinks) --- + 您可以在設定中調整網站的永久連結。 ### 變數 除了下列變數外,您還可使用除了 `:path` 和 `:permalink` 之外 Front-matter 中的所有屬性。 -變數 | 描述 ---- | --- -`:year` | 文章的發表年份(4 位數) -`:month` | 文章的發表月份(2 位數) -`:i_month` | 文章的發表月份(去掉開頭的零) -`:day` | 文章的發表日期 (2 位數) -`:i_day` | 文章的發表日期(去掉開頭的零) -`:hour` | 文章發表時的小時 (2 位數) -`:minute` | 文章發表時的分鐘 (2 位數) -`:second` | 文章發表時的秒鐘 (2 位數) -`:title` | 檔案名稱 (relative to "source/_posts/" folder) -`:name` | 檔案名稱 -`:post_title` | 文章標題 -`:id` | 文章 ID (_not persistent across [cache reset](/zh-tw/docs/commands#clean)_) -`:category` | 分類。如果文章沒有分類,則是 `default_category` 設定。 -`:hash` | SHA1 hash of filename (same as `:title`) and date (12-hexadecimal) +| 變數 | 描述 | +| ------------- | --------------------------------------------------------------------------- | +| `:year` | 文章的發表年份(4 位數) | +| `:month` | 文章的發表月份(2 位數) | +| `:i_month` | 文章的發表月份(去掉開頭的零) | +| `:day` | 文章的發表日期 (2 位數) | +| `:i_day` | 文章的發表日期(去掉開頭的零) | +| `:hour` | 文章發表時的小時 (2 位數) | +| `:minute` | 文章發表時的分鐘 (2 位數) | +| `:second` | 文章發表時的秒鐘 (2 位數) | +| `:title` | 檔案名稱 (relative to "source/\_posts/" folder) | +| `:name` | 檔案名稱 | +| `:post_title` | 文章標題 | +| `:id` | 文章 ID (_not persistent across [cache reset](/zh-tw/docs/commands#clean)_) | +| `:category` | 分類。如果文章沒有分類,則是 `default_category` 設定。 | +| `:hash` | SHA1 hash of filename (same as `:title`) and date (12-hexadecimal) | 您可在 `permalink_defaults` 設定中調整永久連結中各變數的預設值: -``` yaml +```yaml permalink_defaults: lang: en ``` ### 範例 -``` yaml source/_posts/hello-world.md +```yaml source/_posts/hello-world.md title: Hello World date: 2013-07-14 17:01:34 categories: -- foo -- bar + - foo + - bar ``` -設定 | 結果 ---- | --- -`:year/:month/:day/:title/` | 2013/07/14/hello-world/ -`:year-:month-:day-:title.html` | 2013-07-14-hello-world.html -`:category/:title/` | foo/bar/hello-world/ -`:title-:hash/` | hello-world-a2c8ac003b43/ +| 設定 | 結果 | +| ------------------------------- | --------------------------- | +| `:year/:month/:day/:title/` | 2013/07/14/hello-world/ | +| `:year-:month-:day-:title.html` | 2013-07-14-hello-world.html | +| `:category/:title/` | foo/bar/hello-world/ | +| `:title-:hash/` | hello-world-a2c8ac003b43/ | -``` yaml source/_posts/lorem/hello-world.md +```yaml source/_posts/lorem/hello-world.md title: Hello World date: 2013-07-14 17:01:34 categories: -- foo -- bar + - foo + - bar ``` -設定 | 結果 ---- | --- -`:year/:month/:day/:title/` | 2013/07/14/lorem/hello-world/ -`:year/:month/:day/:name/` | 2013/07/14/hello-world/ +| 設定 | 結果 | +| --------------------------- | ----------------------------- | +| `:year/:month/:day/:title/` | 2013/07/14/lorem/hello-world/ | +| `:year/:month/:day/:name/` | 2013/07/14/hello-world/ | ### 多語系支援 若要建立一個多語系的網站,您可修改 `new_post_name` 和 `permalink` 設定,如下: -``` yaml +```yaml new_post_name: :lang/:title.md permalink: :lang/:title/ ``` 當您建立新文章時,文章會被儲存至: -``` bash +```bash $ hexo new "Hello World" --lang tw # => source/_posts/tw/Hello-World.md ``` 而網址會是: -``` plain +```plain http://localhost:4000/tw/hello-world/ ``` diff --git a/source/zh-tw/docs/plugins.md b/source/zh-tw/docs/plugins.md index fe1cf0e661..a74da4b92e 100644 --- a/source/zh-tw/docs/plugins.md +++ b/source/zh-tw/docs/plugins.md @@ -1,6 +1,7 @@ --- title: 外掛 --- + Hexo 有強大的外掛系統,使您能輕鬆擴展功能而不用修改核心模組的原始碼。在 Hexo 中有兩種形式的外掛: ### 腳本(Scripts) @@ -13,7 +14,7 @@ Hexo 有強大的外掛系統,使您能輕鬆擴展功能而不用修改核心 資料夾內至少要包含 2 個檔案:一個是主程式,另一個是 `package.json`,描述套件的用途和相依套件。 -``` plain +```plain . ├── index.js └── package.json @@ -21,7 +22,7 @@ Hexo 有強大的外掛系統,使您能輕鬆擴展功能而不用修改核心 `package.json` 中至少要包含 `name`, `version`, `main` 屬性,例如: -``` json package.json +```json package.json { "name": "hexo-my-plugin", "version": "0.0.1", @@ -45,23 +46,21 @@ Hexo 有強大的外掛系統,使您能輕鬆擴展功能而不用修改核心 1. Fork [hexojs/site] 2. 把檔案庫(repository)複製到電腦上,並安裝相依套件。 - {% code %} - $ git clone https://github.com/<username>/site.git - $ cd site - $ npm install - {% endcode %} + {% code %} + $ git clone https://github.com/<username>/site.git + $ cd site + $ npm install + {% endcode %} 3. 編輯 `source/_data/plugins.yml`,在檔案中新增您的外掛,例如: - {% code %} - - name: hexo-server - description: Server module for Hexo. - link: https://github.com/hexojs/hexo-server - tags: - - official - - server - - console - {% endcode %} + {% code %} + + - name: hexo-server + description: Server module for Hexo. + link: https://github.com/hexojs/hexo-server + tags: - official - server - console + {% endcode %} 4. 推送(push)分支。 5. 建立一個新的合併申請(pull request)。 diff --git a/source/zh-tw/docs/server.md b/source/zh-tw/docs/server.md index ff9e3f94ab..987801331a 100644 --- a/source/zh-tw/docs/server.md +++ b/source/zh-tw/docs/server.md @@ -1,23 +1,24 @@ --- title: Server --- + ## [hexo-server] Hexo 3 把伺服器獨立成個別模組,您必須先安裝 [hexo-server] 才能使用。 -``` bash +```bash $ npm install hexo-server --save ``` 安裝完畢後,輸入以下指令以啟動伺服器,您的網站預設會執行於 `http://localhost:4000`,在伺服器啟動期間,Hexo 會監看檔案變動並自動更新,您無須重啟伺服器。 -``` bash +```bash $ hexo server ``` 如果您想要變更連接埠,或是在執行時遇到了 `EADDRINUSE` 錯誤,可以在執行時使用 `-p` 選項指定其他連接埠。 -``` bash +```bash $ hexo server -p 5000 ``` @@ -25,7 +26,7 @@ $ hexo server -p 5000 在靜態模式下,伺服器只會處理 `public` 資料夾內的檔案,而且不會處理檔案變動,在執行時,您應該先自行執行 `hexo generate`,此模式通常用於生產環境(production)下。 -``` bash +```bash $ hexo server -s ``` @@ -33,7 +34,7 @@ $ hexo server -s 伺服器預設運作在 `0.0.0.0`,您可以覆蓋預設的 IP 設定。 -``` bash +```bash $ hexo server -i 192.168.1.1 ``` diff --git a/source/zh-tw/docs/setup.md b/source/zh-tw/docs/setup.md index 0ac993e0d7..228d386bb7 100644 --- a/source/zh-tw/docs/setup.md +++ b/source/zh-tw/docs/setup.md @@ -6,7 +6,7 @@ title: 建立 一旦 Hexo 完成後,請執行下列指令,Hexo 會在指定資料夾中建立所有您需要的檔案。 -``` bash +```bash $ hexo init <folder> $ cd <folder> $ npm install @@ -14,7 +14,7 @@ $ npm install 建立完成後,專案資料夾會有下列檔案: -``` plain +```plain . ├── _config.yml ├── package.json @@ -25,7 +25,7 @@ $ npm install └── themes ``` -### _config.yml +### \_config.yml 網站 [配置](configuration.html) 檔案,您可以在此配置大部分的設定。 @@ -33,7 +33,7 @@ $ npm install 應用程式資料。[EJS](https://ejs.co/), [Stylus](http://learnboost.github.io/stylus/) 和 [Markdown](http://daringfireball.net/projects/markdown/) renderer 已預設安裝,您可以稍後移除。 -``` json package.json +```json package.json { "name": "hexo-site", "version": "0.0.0", diff --git a/source/zh-tw/docs/syntax-highlight.md b/source/zh-tw/docs/syntax-highlight.md index 65ae0a585e..65df3fdf7b 100644 --- a/source/zh-tw/docs/syntax-highlight.md +++ b/source/zh-tw/docs/syntax-highlight.md @@ -17,7 +17,7 @@ code snippet code snippet {% endcode %} -``` [language] [title] [url] [link text] [additional options] +```[language] [title] [url] [link text] [additional options] code snippet ``` ```` @@ -86,7 +86,7 @@ highlight: auto_detect: false line_number: true line_threshold: 0 - tab_replace: ' ' + tab_replace: " " exclude_languages: - example wrap: true @@ -117,18 +117,18 @@ Hexo adds line number by wrapping output inside `<figure>` and `<table>`: ```html <figure class="highlight yaml"> -<table> -<tbody> -<tr> - <td class="gutter"> - <pre><span class="line">1</span><br></pre> - </td> - <td class="code"> - <pre><span class="line"><span class="attr">hello:</span><span class="string">hexo</span></span><br></pre> - </td> -</tr> -</tbody> -</table> + <table> + <tbody> + <tr> + <td class="gutter"> + <pre><span class="line">1</span><br></pre> + </td> + <td class="code"> + <pre><span class="line"><span class="attr">hello:</span><span class="string">hexo</span></span><br></pre> + </td> + </tr> + </tbody> + </table> </figure> ``` @@ -144,7 +144,6 @@ Accepts an optional threshold to only show line numbers as long as the numbers o Replace tabs inside code block with given string. By default it is 2 spaces. - ### exclude_languages (+6.1.0) Only wrap with `<pre><code class="lang"></code></pre>` and will not render all tags(`span`, and `br`) in content if are languages matches this option. @@ -188,7 +187,7 @@ prismjs: preprocess: true line_number: true line_threshold: 0 - tab_replace: '' + tab_replace: "" ``` Prismjs is disabled by default. You should set `highlight.enable` to `false` before enabling prismjs. diff --git a/source/zh-tw/docs/tag-plugins.md b/source/zh-tw/docs/tag-plugins.md index 038376c11a..04023475f2 100644 --- a/source/zh-tw/docs/tag-plugins.md +++ b/source/zh-tw/docs/tag-plugins.md @@ -1,6 +1,7 @@ --- title: 標籤外掛(Tag Plugins) --- + 標籤外掛和 Front-matter 中的標籤不同,它們是用於在文章中快速插入特定內容的外掛。 雖然你可以以任何格式寫你的文章,但標籤外掛會永遠可用,且語法都會相同。 @@ -81,14 +82,14 @@ code snippet 以 `option:value` 格式設定額外的選項,例如:`line_number:false first_line:5`。 -額外選項 | 說明 | 預設值 ---- | --- | --- -`line_number` | 顯示行號 | `true` -`line_threshold` | 當程式碼區塊的行數超過臨界值時,才顯示行號。 | `0` | -`highlight` | 啟用程式碼強調 | `true` -`first_line` | 設定起始的程式碼行號 | `1` -`mark` | 強調特定的程式碼行號,每個值會以逗點區分。特定的程式碼區間則使用破折號 (dash)<br>範例:`mark:1,4-7,10` 會標示行號 1、 4 到 7 以及 10。 | -`wrap` | 將程式碼區塊包裝在 [`<table>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table) 中 | `true` +| 額外選項 | 說明 | 預設值 | +| ---------------- | -------------------------------------------------------------------------------------------------------------------------------------- | ------ | +| `line_number` | 顯示行號 | `true` | +| `line_threshold` | 當程式碼區塊的行數超過臨界值時,才顯示行號。 | `0` | +| `highlight` | 啟用程式碼強調 | `true` | +| `first_line` | 設定起始的程式碼行號 | `1` | +| `mark` | 強調特定的程式碼行號,每個值會以逗點區分。特定的程式碼區間則使用破折號 (dash)<br>範例:`mark:1,4-7,10` 會標示行號 1、 4 到 7 以及 10。 | +| `wrap` | 將程式碼區塊包裝在 [`<table>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table) 中 | `true` | **普通的程式碼區塊** @@ -136,7 +137,7 @@ _.compact([0, 1, false, 2, '', 3]); ``` {% codeblock _.compact http://underscorejs.org/#compact Underscore.js %} -_.compact([0, 1, false, 2, '', 3]); +\_.compact([0, 1, false, 2, '', 3]); => [1, 2, 3] {% endcodeblock %} @@ -145,9 +146,9 @@ _.compact([0, 1, false, 2, '', 3]); 另一種形式的程式碼區塊。 {% raw %} -```[language] [title] [url] [link text] +``[language] [title] [url] [link text] code snippet -``` +`` {% endraw %} ## 抬升式引用區塊 (Pull Quote) @@ -301,6 +302,7 @@ content ``` {% post_link hexo-4-released 'How to use <b> tag in title' %} ``` + {% post_link hexo-4-released 'How to use <b> tag in title' %} **不要逸出標題。** @@ -308,6 +310,7 @@ content ``` {% post_link hexo-4-released '<b>bold</b> custom title' false %} ``` + {% post_link hexo-4-released '<b>bold</b> custom title' false %} ## 引用資產 @@ -330,32 +333,32 @@ _hexo-renderer-marked 3.1.0+ 可以(可選的)自動解析文章內的圖片 `{% asset_img foo.jpg %}` -``` html -<img src="/2020/01/02/hello/foo.jpg"> +```html +<img src="/2020/01/02/hello/foo.jpg" /> ``` **自訂 Class** `{% asset_img post-image foo.jpg %}` -``` html -<img src="/2020/01/02/hello/foo.jpg" class="post-image"> +```html +<img src="/2020/01/02/hello/foo.jpg" class="post-image" /> ``` **顯示尺寸** `{% asset_img foo.jpg 500 400 %}` -``` html -<img src="/2020/01/02/hello/foo.jpg" width="500" height="400"> +```html +<img src="/2020/01/02/hello/foo.jpg" width="500" height="400" /> ``` **標題及替代文字** `{% asset_img logo.svg "lorem ipsum'dolor'" %}` -``` html -<img src="/2020/01/02/hello/foo.jpg" title="lorem ipsum" alt="dolor"> +```html +<img src="/2020/01/02/hello/foo.jpg" title="lorem ipsum" alt="dolor" /> ``` ## URL @@ -370,23 +373,23 @@ _hexo-renderer-marked 3.1.0+ 可以(可選的)自動解析文章內的圖片 **範例:** -``` yml +```yml _config.yml root: /blog/ # 範例 ``` -``` +``` {% url_for blog index.html %} ``` -``` html +```html <a href="/blog/index.html">blog</a> ``` 相對路徑連結則預設依照選項 `relative_link` 例如:post/page 路徑是 '/foo/bar/index.html' -``` yml +```yml _config.yml relative_link: true ``` @@ -395,7 +398,7 @@ relative_link: true {% url_for blog index.html %} ``` -``` html +```html <a href="../../index.html">blog</a> ``` @@ -405,7 +408,7 @@ relative_link: true {% url_for blog index.html false %} ``` -``` html +```html <a href="/index.html">blog</a> ``` @@ -419,7 +422,7 @@ relative_link: true **範例:** -``` yml +```yml _config.yml url: https://example.com/blog # 範例 ``` @@ -428,7 +431,7 @@ url: https://example.com/blog # 範例 {% full_url_for index /a/path %} ``` -``` html +```html <a href="https://example.com/blog/a/path">index</a> ``` @@ -446,11 +449,10 @@ content 使用在 `<!-- more -->` 標籤之前的文字作為為這篇文章的摘要。[front-matter](/docs/front-matter#Settings-amp-Their-Default-Values) 中的 `excerpt:` 值如果被特指的話,將會將其優先使用。 - **範例:** ``` Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. <!-- more --> Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. -``` \ No newline at end of file +``` diff --git a/source/zh-tw/docs/templates.md b/source/zh-tw/docs/templates.md index e403d46133..44bbb9c1fa 100644 --- a/source/zh-tw/docs/templates.md +++ b/source/zh-tw/docs/templates.md @@ -1,38 +1,43 @@ --- title: 模版 --- + 模板決定了網站內容的呈現方式,每個主題至少都應包含一個 `index` 模板,以下是各頁面相對應的模板名稱: -模板 | 用途 | Fallback ---- | --- | --- -`index` | 首頁 | -`post` | 文章 | `index` -`page` | 分頁 | `index` -`archive` | 彙整 | `index` -`category` | 分類彙整 | `archive` -`tag` | 標籤彙整 | `archive` +| 模板 | 用途 | Fallback | +| ---------- | -------- | --------- | +| `index` | 首頁 | +| `post` | 文章 | `index` | +| `page` | 分頁 | `index` | +| `archive` | 彙整 | `index` | +| `category` | 分類彙整 | `archive` | +| `tag` | 標籤彙整 | `archive` | ## 佈局(Layout) 如果頁面結構類似,例如兩個模板都有頁首(Header)和頁尾(Footer),您可考慮透過「佈局」讓兩個模板共享相同的結構。一個佈局檔案必須要能顯示 `body` 變數的內容,如此一來模板的內容才會被顯示,舉例來說: -``` html index.ejs +```html index.ejs index ``` -``` html layout.ejs -<!DOCTYPE html> +```html layout.ejs +<!doctype html> <html> - <body><%- body %></body> + <body> + <%- body %> + </body> </html> ``` 產生: -``` html -<!DOCTYPE html> +```html +<!doctype html> <html> - <body>index</body> + <body> + index + </body> </html> ``` @@ -42,18 +47,18 @@ index 局部模板讓您在不同模板之間共享相同的組件,例如頁首(Header)、頁尾(Footer)或側邊欄(Sidebar)等,可利用局部模板功能分割為個別檔案,讓維護更加便利。舉例來說: -``` html partial/header.ejs +```html partial/header.ejs <h1 id="logo"><%= config.title %></h1> ``` -``` html index.ejs +```html index.ejs <%- partial('partial/header') %> <div id="content">Home page</div> ``` 產生: -``` html +```html <h1 id="logo">My Site</h1> <div id="content">Home page</div> ``` @@ -62,18 +67,18 @@ index 您可以在模板中指定區域變數,就能在其他模板中使用。 -``` html partial/header.ejs +```html partial/header.ejs <h1 id="logo"><%= title></h1> ``` -``` html index.ejs +```html index.ejs <%- partial('partial/header', {title: 'Hello World'}) %> <div id="content">Home page</div> ``` 產生: -``` html +```html <h1 id="logo">Hello World</h1> <div id="content">Home page</div> ``` @@ -86,7 +91,7 @@ index 它可用於頁首、頁尾、側邊欄等資料不常變動的位置,舉例來說: -``` js +```js <%- fragment_cache('header', function(){ return '<header></header>'; }); @@ -94,7 +99,7 @@ index 如果您使用局部模板的話,可以更簡單: -``` js +```js <%- partial('header', {}, {cache: true}); ``` diff --git a/source/zh-tw/docs/themes.md b/source/zh-tw/docs/themes.md index aeb5d9ee79..1d8f249fc7 100644 --- a/source/zh-tw/docs/themes.md +++ b/source/zh-tw/docs/themes.md @@ -1,9 +1,10 @@ --- title: 主題 --- + 打造 Hexo 主題非常容易,您只要在 `themes` 資料夾內,新增一個資料夾,並修改 `_config.yml` 內的 `theme` 設定,即可切換主題。一個主題可能會有以下的結構: -``` plain +```plain . ├── _config.yml ├── languages @@ -12,7 +13,7 @@ title: 主題 └── source ``` -### _config.yml +### \_config.yml 主題的配置檔案。Unlike the site's primary configuration file, 主題的配置檔案修改時會自動更新,無需重啟 Hexo 伺服器。 @@ -24,7 +25,7 @@ title: 主題 佈局資料夾。用於放置主題的模板檔案,決定了網站內容的呈現方式,Hexo 內建 [Nunjucks] 模板引擎,您可另外安裝外掛來獲得 [EJS]、或 [Pug] 支援,Hexo 根據模板檔案的副檔名來決定所使用的模板引擎,例如: -``` plain +```plain EJS: layout.ejs Swig: layout.swig ``` @@ -48,26 +49,22 @@ Swig: layout.swig 1. Fork [hexojs/site] 2. 把檔案庫(repository)複製到電腦上,並安裝相依套件。 - {% code %} - $ git clone https://github.com/<username>/site.git - $ cd site - $ npm install - {% endcode %} + {% code %} + $ git clone https://github.com/<username>/site.git + $ cd site + $ npm install + {% endcode %} 3. 編輯 `source/_data/themes.yml`,在檔案中新增您的主題,例如: - {% code %} - - name: landscape - description: A brand new default theme for Hexo. - link: https://github.com/hexojs/hexo-theme-landscape - preview: http://hexo.io/hexo-theme-landscape - tags: - - official - - responsive - - widget - - two_column - - one_column - {% endcode %} + {% code %} + + - name: landscape + description: A brand new default theme for Hexo. + link: https://github.com/hexojs/hexo-theme-landscape + preview: http://hexo.io/hexo-theme-landscape + tags: - official - responsive - widget - two_column - one_column + {% endcode %} 4. 在 `source/themes/screenshots` 新增同名的截圖檔案,圖片必須為 800x500 的 PNG 檔案。 5. 推送(push)分支。 diff --git a/source/zh-tw/docs/troubleshooting.md b/source/zh-tw/docs/troubleshooting.md index 8fd38ebfa8..e3877c0b20 100644 --- a/source/zh-tw/docs/troubleshooting.md +++ b/source/zh-tw/docs/troubleshooting.md @@ -1,18 +1,19 @@ --- title: 解決問題 --- + 在使用 Hexo 時,您可能會遇到一些問題,下列的常見問題解答可能會對您有所幫助。如果您在這裡找不道解答,可以在 [GitHub](https://github.com/hexojs/hexo/issues) 或 [Google Group](https://groups.google.com/group/hexo) 上詢問。 ## YAML 解析錯誤 -``` plain +```plain JS-YAML: incomplete explicit mapping pair; a key node is missed at line 18, column 29: last_updated: Last updated: %s ``` 如果 YAML 字串中包含冒號(`:`)的話,請加上引號。 -``` plain +```plain JS-YAML: bad indentation of a mapping entry at line 18, column 31: last_updated:"Last updated: %s" ``` @@ -23,13 +24,13 @@ JS-YAML: bad indentation of a mapping entry at line 18, column 31: ## EMFILE 錯誤 -``` plain +```plain Error: EMFILE, too many open files ``` 雖然 Node.js 有非阻塞 I/O,同步 I/O 的數量仍被系統所限制,在產生大量靜態檔案的時候,您可能會碰到 EMFILE 錯誤,您可試著提高同步 I/O 的限制來解決此問題。 -``` bash +```bash $ ulimit -n 10000 ``` @@ -37,7 +38,7 @@ $ ulimit -n 10000 If you encounter the following error: -``` bash +```bash $ ulimit -n 10000 ulimit: open files: cannot modify limit: Operation not permitted ``` @@ -48,29 +49,29 @@ To override the limit: 1. Add the following line to "/etc/security/limits.conf": - ``` - * - nofile 10000 +``` +* - nofile 10000 - # '*' applies to all users and '-' set both soft and hard limits - ``` +# '*' applies to all users and '-' set both soft and hard limits +``` - * The above setting may not apply in some cases, ensure "/etc/pam.d/login" and "/etc/pam.d/lightdm" have the following line. (Ignore this step if those files do not exist) +- The above setting may not apply in some cases, ensure "/etc/pam.d/login" and "/etc/pam.d/lightdm" have the following line. (Ignore this step if those files do not exist) - ``` - session required pam_limits.so - ``` +``` +session required pam_limits.so +``` 2. If you are on a [systemd-based](https://en.wikipedia.org/wiki/Systemd#Adoption) distribution, systemd may override "limits.conf". To set the limit in systemd, add the following line in "/etc/systemd/system.conf" and "/etc/systemd/user.conf": - ``` - DefaultLimitNOFILE=10000 - ``` +``` +DefaultLimitNOFILE=10000 +``` 3. Reboot ## Git 佈署問題 -``` plain +```plain fatal: 'username.github.io' does not appear to be a git repository ``` @@ -78,19 +79,19 @@ fatal: 'username.github.io' does not appear to be a git repository ## 伺服器問題 -``` plain +```plain Error: listen EADDRINUSE ``` 您可能同時開啟兩個 Hexo 伺服器,或者有其他應用程式正在佔用相同的連接埠,請試著修改 `port` 設定,或是在啟動 Hexo 伺服器時加上 `-p` 選項。 -``` bash +```bash $ hexo server -p 5000 ``` ## 外掛安裝問題 -``` plain +```plain npm ERR! node-waf configure build ``` @@ -109,13 +110,13 @@ Hexo 使用 [Warehouse] 儲存資料,它不是一般陣列所以必須先轉 有時資料可能沒有被更新,或是產生出的檔案與修改前的相同,您可試著清除快取並再試一次。 -``` bash +```bash $ hexo clean ``` ## 脫逸(Escape)內容 -Hexo 使用 [Nunjucks] 來解析文章(舊版本使用 [Swig],兩者語法類似),內容若包含 `{{ }}` 或 `{% %}` 可能導致解析錯誤,您可以用 [`raw`](/docs/tag-plugins#Raw) 標籤包裹,single backtick ```` `{{ }}` ```` 或 triple backtick 來避免潛在問題發生。 +Hexo 使用 [Nunjucks] 來解析文章(舊版本使用 [Swig],兩者語法類似),內容若包含 `{{ }}` 或 `{% %}` 可能導致解析錯誤,您可以用 [`raw`](/docs/tag-plugins#Raw) 標籤包裹,single backtick `` `{{ }}` `` 或 triple backtick 來避免潛在問題發生。 Alternatively, Nunjucks tags can be disabled through the renderer's option (if supported), [API](/api/renderer#Disable-Nunjucks-tags) or [front-matter](/docs/front-matter). ``` @@ -156,7 +157,7 @@ Error: watch /path/to/hexo/theme/ EMPERM Unfortunately, WSL does not currently support filesystem watchers. Therefore, the live updating feature of hexo's server is currently unavailable. You can still run the server from a WSL environment by first generating the files and then running it as a static server: -``` sh +```sh $ hexo generate $ hexo server -s ``` diff --git a/source/zh-tw/docs/variables.md b/source/zh-tw/docs/variables.md index 1d6cd43896..0ec6de7e72 100644 --- a/source/zh-tw/docs/variables.md +++ b/source/zh-tw/docs/variables.md @@ -1,17 +1,18 @@ --- title: 變數 --- + ### 全局變數 -變數 | 描述 ---- | --- -`site` | [網站變數](#網站變數) -`page` | 針對該頁面的資訊以及 front-matter 所設定的變數。 -`config` | 網站配置 -`theme` | 主題配置。繼承自網站配置。 -`path` | 目前頁面的路徑(不含根路徑) -`url` | 目前頁面的完整網址 -`env` | 環境變數 +| 變數 | 描述 | +| -------- | ------------------------------------------------ | +| `site` | [網站變數](#網站變數) | +| `page` | 針對該頁面的資訊以及 front-matter 所設定的變數。 | +| `config` | 網站配置 | +| `theme` | 主題配置。繼承自網站配置。 | +| `path` | 目前頁面的路徑(不含根路徑) | +| `url` | 目前頁面的完整網址 | +| `env` | 環境變數 | {% note warn %} Lodash has been removed from global variables since Hexo 5.0.0. [You-Dont-Need-Lodash-Underscore](https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore) might be helpful for your migration. @@ -19,72 +20,72 @@ Lodash has been removed from global variables since Hexo 5.0.0. [You-Dont-Need-L ### 網站變數 -變數 | 描述 ---- | --- -`site.posts` | 所有文章 -`site.pages` | 所有分頁 -`site.categories` | 所有分類 -`site.tags` | 所有標籤 +| 變數 | 描述 | +| ----------------- | -------- | +| `site.posts` | 所有文章 | +| `site.pages` | 所有分頁 | +| `site.categories` | 所有分類 | +| `site.tags` | 所有標籤 | ### 頁面變數 **文章(post, page, ...)** -變數 | 描述 ---- | --- -`page.title` | 文章標題 -`page.date` | 文章建立日期([Moment.js] 物件) -`page.updated` | 文章更新日期([Moment.js] 物件) -`page.categories` | 文章分類 -`page.tags` | 文章標籤 -`page.comments` | 留言是否開啟 -`page.layout` | 佈局名稱 -`page.content` | 文章的完整內容 -`page.excerpt` | 文章摘要 -`page.more` | 除了文章摘要的其餘內容 -`page.source` | 文章原始路徑 -`page.full_source` | 文章的完整原始路徑 -`page.path` | 文章網址(不含根路徑)。我們通常在主題中使用 `url_for(page.path)`。 -`page.permalink` | 文章的完整網址 -`page.prev` | 上一篇文章。如果此為第一篇文章則為 `null`。 -`page.next` | 下一篇文章。如果此為最後一篇文章則為 `null`。 -`page.raw` | 文章的原始內容 -`page.photos` | 文章的照片(用於相簿) -`page.link` | 文章的外連連結(用於連結文章) +| 變數 | 描述 | +| ------------------ | ------------------------------------------------------------------- | +| `page.title` | 文章標題 | +| `page.date` | 文章建立日期([Moment.js] 物件) | +| `page.updated` | 文章更新日期([Moment.js] 物件) | +| `page.categories` | 文章分類 | +| `page.tags` | 文章標籤 | +| `page.comments` | 留言是否開啟 | +| `page.layout` | 佈局名稱 | +| `page.content` | 文章的完整內容 | +| `page.excerpt` | 文章摘要 | +| `page.more` | 除了文章摘要的其餘內容 | +| `page.source` | 文章原始路徑 | +| `page.full_source` | 文章的完整原始路徑 | +| `page.path` | 文章網址(不含根路徑)。我們通常在主題中使用 `url_for(page.path)`。 | +| `page.permalink` | 文章的完整網址 | +| `page.prev` | 上一篇文章。如果此為第一篇文章則為 `null`。 | +| `page.next` | 下一篇文章。如果此為最後一篇文章則為 `null`。 | +| `page.raw` | 文章的原始內容 | +| `page.photos` | 文章的照片(用於相簿) | +| `page.link` | 文章的外連連結(用於連結文章) | **首頁(index)** -變數 | 描述 ---- | --- -`page.per_page` | 每頁顯示的文章數量 -`page.total` | 總頁數 -`page.current` | 目前頁數 -`page.current_url` | 目前分頁的網址 -`page.posts` | 本頁文章 -`page.prev` | 上一頁的頁數。如果此頁是第一頁的話則為 `0`。 -`page.prev_link` | 上一頁的連結。如果此頁是第一頁的話則為 `''`。 -`page.next` | 下一頁的頁數。如果此頁是最後一頁的話則為 `0`。 -`page.next_link` | 下一頁的網址。如果此頁是最後一頁的話則為 `''`。 -`page.path` | 目前頁面的路徑(不含根目錄)。我們通常在主題中使用 `url_for(page.path)`。 +| 變數 | 描述 | +| ------------------ | ------------------------------------------------------------------------- | +| `page.per_page` | 每頁顯示的文章數量 | +| `page.total` | 總頁數 | +| `page.current` | 目前頁數 | +| `page.current_url` | 目前分頁的網址 | +| `page.posts` | 本頁文章 | +| `page.prev` | 上一頁的頁數。如果此頁是第一頁的話則為 `0`。 | +| `page.prev_link` | 上一頁的連結。如果此頁是第一頁的話則為 `''`。 | +| `page.next` | 下一頁的頁數。如果此頁是最後一頁的話則為 `0`。 | +| `page.next_link` | 下一頁的網址。如果此頁是最後一頁的話則為 `''`。 | +| `page.path` | 目前頁面的路徑(不含根目錄)。我們通常在主題中使用 `url_for(page.path)`。 | **彙整 (archive)**:與 `index` 佈局相同,但新增以下變數。 -變數 | 描述 ---- | --- -`archive` | 等於 `true` -`year` | 彙整年份(4 位數) -`month` | 彙整月份(不含開頭的零) +| 變數 | 描述 | +| --------- | ------------------------ | +| `archive` | 等於 `true` | +| `year` | 彙整年份(4 位數) | +| `month` | 彙整月份(不含開頭的零) | **分類 (category)**:與 `index` 佈局相同,但新增以下變數。 -變數 | 描述 ---- | --- -`category` | 分類名稱 +| 變數 | 描述 | +| ---------- | -------- | +| `category` | 分類名稱 | **標籤 (tag)**:與 `index` 佈局相同,但新增以下變數。 -變數 | 描述 ---- | --- -`tag` | 標籤名稱 +| 變數 | 描述 | +| ----- | -------- | +| `tag` | 標籤名稱 | [Moment.js]: http://momentjs.com/ diff --git a/source/zh-tw/docs/writing.md b/source/zh-tw/docs/writing.md index 30e7c128af..18237f78b9 100644 --- a/source/zh-tw/docs/writing.md +++ b/source/zh-tw/docs/writing.md @@ -6,7 +6,7 @@ title: 寫作 接下來,我們要在網誌中建立第一篇新文章,您可以直接從現有的範例文章「Hello World」改寫,但我們更建議您學習 `new` 指令。 -``` bash +```bash $ hexo new [layout] <title> ``` @@ -16,11 +16,11 @@ $ hexo new [layout] <title> Hexo 有三種預設佈局:`post`、`page` 和 `draft`,它們分別對應不同的路徑,而您所自定的其他佈局和 `post` 相同,都儲存至 `source/_posts` 資料夾。 -佈局 | 路徑 ---- | --- -`post` | `source/_posts` -`page` | `source` -`draft` | `source/_drafts` +| 佈局 | 路徑 | +| ------- | ---------------- | +| `post` | `source/_posts` | +| `page` | `source` | +| `draft` | `source/_drafts` | {% note tip Disabling layout %} If you don't want an article (post/page) to be processed with a theme, set `layout: false` in its front-matter. Refer to [this section](/zh-tw/docs/front-matter#佈局) for more details. @@ -30,20 +30,20 @@ If you don't want an article (post/page) to be processed with a theme, set `layo Hexo 預設以標題做為檔案名稱,但您可編輯 `new_post_name` 設定來變更預設的檔案名稱,舉例來說,設為 `:year-:month-:day-:title.md` 可讓您更方便的透過日期來管理文章。 -變數 | 描述 ---- | --- -`:title` | 標題 -`:year` | 建立年份(4 位數) -`:month` | 建立月份(2 位數) -`:i_month` | 建立月份(去掉開頭的零) -`:day` | 建立日期(2 位數) -`:i_day` | 建立日期(去掉開頭的零) +| 變數 | 描述 | +| ---------- | ------------------------ | +| `:title` | 標題 | +| `:year` | 建立年份(4 位數) | +| `:month` | 建立月份(2 位數) | +| `:i_month` | 建立月份(去掉開頭的零) | +| `:day` | 建立日期(2 位數) | +| `:i_day` | 建立日期(去掉開頭的零) | ### 草稿 剛剛提到了 Hexo 的一種特殊佈局:`draft`,這種佈局在建立時會被儲存於 `source/_drafts` 資料夾,您可透過 `publish` 指令將草稿移動到 `source/_posts` 資料夾,這項指令的使用方式與 `new` 十分類似,您也可在指令中指定 `layout` 來指定佈局。 -``` bash +```bash $ hexo publish [layout] <title> ``` @@ -53,17 +53,17 @@ $ hexo publish [layout] <title> 在建立文章時,Hexo 會根據 `scaffolds` 資料夾內相對應的檔案來建立檔案,例如: -``` bash +```bash $ hexo new photo "My Gallery" ``` 在執行這行指令時,Hexo 會嘗試在 `scaffolds` 資料夾中找尋 `photo.md`,並根據其內容建立文章,以下是您可在鷹架中使用的變數: -變數 | 描述 ---- | --- -`layout` | 佈局 -`title` | 標題 -`date` | 檔案建立日期 +| 變數 | 描述 | +| -------- | ------------ | +| `layout` | 佈局 | +| `title` | 標題 | +| `date` | 檔案建立日期 | ### Supported Formats diff --git a/source/zh-tw/index.md b/source/zh-tw/index.md index 7bf4361025..b7d89618bc 100644 --- a/source/zh-tw/index.md +++ b/source/zh-tw/index.md @@ -38,4 +38,4 @@ comments: false <p class="intro-feature-desc">Hexo 有強大的外掛系統,您可安裝外掛讓 Hexo 支援 Jade, CoffeeScript。</p> </div> </li> -</ul> \ No newline at end of file +</ul>