Loading...

Loading...

Customization

This page explains how to add your own things to the blog: custom JS/CSS, the inject_point mechanism, custom tag plugins, and how theme config is overridden. Editing code is a “developer-level” operation — read the Installation & Theme Config chapter first to understand the directory structure, and pick a release method per the Deployment chapter when done.

Core principle: don’t modify the theme source unless you have to. Prefer inject_point injection and config overrides — theme upgrades (submodule themes/matery/) won’t drag you into conflicts.

How to read: each section follows “How to enable → Common options → All tunable keys → Boundaries & conflicts” — first the Effect (what shows on the page, what appears in the output), then the corresponding source/config that produces it. Copy and use.

1. Custom JS/CSS

Purpose: append scripts and styles site-wide or per-page; the most common kind of customization.

Learning path: How to enable → Common options → All tunable keys → Boundaries & conflicts

1.1 How to enable

Effect: only the page that writes the reference loads the my-custom.css rules and runs the my-custom.js code (e.g. one extra console log line); other pages are unaffected.

Corresponding source (post/page body; replace the path with your actual file):

<!-- reference directly in the post/page body -->
<link rel="stylesheet" href="/js/my-custom.css">
<script src="/js/my-custom.js" defer></script>

Output: files placed under source/js/, source/css/ or any directory are copied as-is to the matching public/ path at build time (i.e. source/js/my-custom.js → public/js/my-custom.js), and the page fetches them at the path written above.

1.2 Common options

① HTML inside skip_render directories stays as-is

Effect: files in these directories aren’t rendered by Hexo and are copied as-is to public/ — good for standalone HTML pages; plain .js/.css are never rendered anyway, so they’re unaffected.

Corresponding config (root _config.yml, skip_render section, excerpt):

skip_render:
  - 'nav/**'
  - 'js/**'
  - 'libs/**'
  - 'live2d/**'
  - 'medias_webp/**'
  - 'html-file/**/*.html'

② Keep relative paths when going through a CDN

Effect: paths starting with / such as /js/xxx.js point at the site’s own domain, not the CDN domain; the CDN only applies to theme assets listed in the theme config cdn section.

Corresponding config (theme config cdn section; see the Global Configuration chapter):

cdn:
  url: "{cdnUrl}"          # JS/CSS CDN URL
  mediaUrl: "{mediaUrl}"   # image/media CDN URL
  resUrl: "{resUrl}"       # asset CDN URL

③ Don’t want a per-page reference → use inject points or config keys

Effect: the script/style applies to every page without polluting theme template files.

Corresponding approach: inject points in §2, custom_js / custom_css in §5.

1.3 All tunable keys

ApproachScopeFile locationTheme source changes
<link>/<script> in the pageSingle pagesource/js/, source/css/No
inject_point injectionSite-widethemes/matery/scripts/filters/Yes (new script file)
custom_js / custom_css configSite-widesource/js/, source/css/ + config templateNo (config only)

1.4 Boundaries & conflicts

  • Directories under source/ covered by skip_render (nav/, static directories other than docs/, live2d/, etc.) are not rendered; custom HTML placed there stays as-is. Plain .js/.css are unaffected.
  • Referencing the same script through both custom_js and an in-page <script> loads it twice — pick one.

1.5 Summary

  • Minimum viable: fill one path each for custom_js / custom_css (§5)
  • Single page only: <link>/<script> in the page, leave globals alone
  • Fixed insertion position: use inject_point (§2)
  • Change didn’t take effect: confirm the file was copied to public/ first, then clear the cache per the FAQ chapter

2. The inject_point Mechanism

Purpose: insert HTML/JS/CSS at fixed page positions without modifying theme templates. The theme inherited an injection system from NexT; layout/layout.ejs actually uses 3 view injection points.

Learning path: How to enable → Common options → All tunable keys → Boundaries & conflicts

2.1 How to enable

Effect: every page (home, post, standalone page) gains your injected block just before </body> — e.g. a global script tag or an analytics snippet.

Corresponding source (themes/matery/layout/layout.ejs):

<!-- layout.ejs -->
<%- inject_point('bodyBegin') %>   <!-- start of <body> -->
<%- inject_point('header') %>      <!-- header position -->
<%- inject_point('bodyEnd') %>     <!-- before </body> -->

2.2 Common options

① Register a global script (raw)

Effect: the bodyEnd position outputs <script src="/js/my-custom.js" defer></script> as-is, so every page site-wide carries the tag.

Corresponding source (new file themes/matery/scripts/filters/my-injects.js):

// themes/matery/scripts/filters/my-injects.js
'use strict';

const path = require('path');

hexo.extend.filter.register('theme_inject', function(injects) {
  // file(name, file-path): register a template file (extension from the file when name has none; path relative to the hexo root)
  injects.bodyEnd.file('my-custom', path.join(hexo.theme_dir, 'layout/_partial/common/my-custom.ejs'));
  // raw(name, content-string): register HTML/JS content directly
  injects.bodyEnd.raw('my-analytics', '<script src="/js/my-custom.js" defer></script>');
}, -99); // -99 = run first, consistent with default-injects.js

Output: the contents of layout/_partial/common/my-custom.ejs are rendered as-is at the <%- inject_point('bodyEnd') %> location; strings registered via raw are output directly, without going through a template.

② Control the order of multiple injections at the same point

Effect: the smaller order is, the earlier the output; when several scripts are registered at the same point, it decides which runs first.

Corresponding source:

injects.bodyEnd.raw('my-analytics', '<script src="/js/a.js"></script>', {}, {}, 10);

In injects.<point>.file(name, path, locals, options, order) the third argument onward is locals/options/order.

③ Change the injection position

Effect: move the content from the page footer to the head (headEnd) or above post metadata (postMetaTop) — where it appears on the page changes accordingly.

Corresponding source:

injects.headEnd.raw('my-meta', '<meta name="my-flag" content="1">');
injects.postMetaTop.raw('my-badge', '<span class="chip">Proofread</span>');

Where injection points are actually called (all 12 are called in templates):

  • headEnd (head.ejs), footer (footer.ejs)
  • bodyBegin/header/bodyEnd (layout.ejs)
  • postMetaTop/postMarkdownBegin/postMarkdownEnd/postCopyright/postComments (post-detail.ejs)
  • pageComments (bb/msg), linksComments (friends)

postMetaBottom/postLeft/postRight have been removed from the injection-point definitions (not “defined but not called”; comment pages fall back via inject_point('pageComments') || partial('_partial/comments')).

④ Injection points inside the post body

Effect: content appears at the start/end of the post body block (postMarkdownBegin / postMarkdownEnd) and scrolls with the article instead of sticking to the page header/footer.

Corresponding source:

injects.postMarkdownBegin.raw('my-before', '<div class="notice">Body starts</div>');
injects.postMarkdownEnd.raw('my-after', '<div class="notice">Body ends</div>');

2.3 All tunable keys

OptionTypeDefaultValues / rangePurpose
injects.<point>.raw(name, html, locals?, options?, order?)method—any HTML stringregister content directly
injects.<point>.file(name, path, locals?, options?, order?)method—absolute path to a template fileregister a template file
ordernumberregistration ordersmaller outputs firstsort multiple injections at the same point
theme_inject filter prioritynumber—e.g. -99determines callback execution order (matches default-injects.js)

2.4 Boundaries & conflicts

  • Injected content is not an HTML string loaded from theme config — hexo scripts register it into a runtime registry via the theme_inject filter. scripts/events/lib/injects.js runs hexo.execFilterSync('theme_inject', injects) before generation and writes the result into theme.config.injects; the inject_point helper (scripts/helpers/engine.js) reads that registry at render time and outputs it.
  • Style injection points (variable/mixin/style) are a separate mechanism: they register .styl file paths, injected at Stylus compile time — don’t mix them with view injection points.
  • Injected content is output as-is; use defer on <script> tags (see the LCP layering principle in the Performance Optimization chapter).

2.5 Summary

  • Minimum viable: one injects.bodyEnd.raw(...) is enough
  • Reusable template: point .file(...) at an EJS file under _partial/
  • Wrong position: confirm the injection point’s spelling and check the call-site list in §2.2
  • Style injection: that’s Stylus’s style injection point — don’t mix it with view injection points

3. Custom Tag Plugins

Purpose: use shortcodes in Markdown to generate complex HTML. The theme ships 14 tag plugins (note/tabs/timeline/mermaid/pdf/github-card etc.; usage in the Tag Plugins chapter) — write your own when they’re not enough.

Learning path: How to enable → Common options → All tunable keys → Boundaries & conflicts

3.1 How to enable

Effect: {% mybox Notice %} in a post renders as a card with a title (<div class="my-box">), and Markdown inside the card body renders normally (**bold** becomes bold) instead of showing the raw shortcode.

Corresponding source (new file themes/matery/scripts/tags/mybox.js):

// themes/matery/scripts/tags/mybox.js
'use strict';

function mybox(args, content) {
  const title = args.join(' ') || 'Note';
  return `<div class="my-box"><strong>${title}</strong><div class="my-box-body">${hexo.render.renderSync({ text: content, engine: 'markdown' })}</div></div>`;
}

hexo.extend.tag.register('mybox', mybox, { ends: true });

Usage (post body):

{% mybox Notice %}
Write **any Markdown** here; it renders as the card content.
{% endmybox %}

Output: the built HTML contains <div class="my-box"><strong>Notice</strong><div class="my-box-body"><p>Write <strong>any Markdown</strong>…</p></div></div>.

3.2 Common options

① Inline tag (no closing tag)

Effect: outputs a single HTML fragment with no {% endmybox %} needed — good for badges, icons and other single-line content.

Corresponding source:

function mybadge(args) {
  return `<span class="my-badge">${args[0] || 'NEW'}</span>`;
}
hexo.extend.tag.register('mybadge', mybadge);   // no ends = inline

Output: {% mybadge Trending %} in a post → <span class="my-badge">Trending</span>.

② Don’t render Markdown, keep raw text

Effect: symbols like ** inside content stay as-is and no longer become <strong>.

Corresponding source:

function rawbox(args, content) {
  return `<pre class="raw-box">${content}</pre>`;
}
hexo.extend.tag.register('rawbox', rawbox, { ends: true });

③ Plugin name and filename

Effect: the filename is the plugin name — mybox.js registers mybox, so posts write {% mybox %}; renaming the file renames the shortcode.

Corresponding source: no config option; it comes from the first argument of hexo.extend.tag.register('mybox', ...).

3.3 All tunable keys

OptionTypeDefaultValues / rangePurpose
register(name, fn)method—name string + functionregister an inline tag
options.endsboolfalsetrue / falsetrue requires a closing {% endxxx %}
contentstring—raw text between tagsblock tag content (render Markdown yourself)
argsarray[]space-separated argumentsargument list after the tag name

3.4 Boundaries & conflicts

  • { ends: true } means a closing {% endmybox %} is required; omitting the end tag fails the build (an unknown block tag style error).
  • content is raw text by default; to render Markdown use hexo.render.renderSync (note this is a Hexo internal API that only runs at build time).
  • The filename is the plugin name (mybox.js → {% mybox %}); after changes always run hexo clean && hexo generate (see cache issues in the FAQ chapter).
  • To be globally available without touching theme source, putting the file in the theme scripts/ is the only way (the theme is a submodule, so changes need dual-repo commits — see the Deployment chapter).

3.5 Summary

  • Minimum viable: one hexo.extend.tag.register(...) file
  • Needs closing tag: { ends: true } + {% endxxx %}
  • Needs Markdown: run content through hexo.render.renderSync
  • No effect after change: run hexo clean then generate again

4. Theme Config Override (Template Injection Mechanism)

Purpose: theme config is generated dynamically at CI build time — userConfig/_config.tmp.yml is the template, copied to themes/matery/_config.yml at build time with placeholders replaced. Theme config changes must go in the template; editing themes/matery/_config.yml directly gets overwritten.

Learning path: How to enable → Common options → All tunable keys → Boundaries & conflicts

4.1 How to enable

Effect: add/change a key in the template, run one build, and the same key shows up in themes/matery/_config.yml with placeholders already replaced by real URLs/version numbers; if you only edit themes/matery/_config.yml, it is reverted on the next build.

Corresponding command:

tools/cicd.sh -d          # inside the container: config injection + build (no push)
grep -n "myFeature" themes/matery/_config.yml   # verify the injection result

Output: grep prints the key you wrote in userConfig/_config.tmp.yml, proving the template override took effect.

4.2 Common options

① Template placeholders

Effect: curly-brace placeholders in the template are replaced after build with versioned CDN URLs; the source template keeps the placeholders untouched.

Corresponding config (replaced by tools/cicd.sh via sed):

PlaceholderReplaced withExample
{cdnPathVersion}jsDelivr versioned pathhttps://cdn.jsdelivr.net/gh/appotry/hexo@1.1
{cdnPathLatest}latest CDN pathhttps://cdn.jsdelivr.net/gh/appotry/hexo@latest
{urlVersion}file version number?v={urlVersion}
{cdnUrl} / {mediaUrl} / {resUrl}CDN domainshttps://cfblog.17lai.site

② Full chain for a custom config item

Effect: after adding a myFeature switch, EJS templates can read theme.myFeature.enable, Stylus can read theme-config("myFeature.text"), and the page renders according to the config.

Corresponding config:

  1. Template userConfig/_config.tmp.yml add the key:
    myFeature:
      enable: true
      text: Hello
  2. Read in Stylus (under themes/matery/source/css/):
    $my-feature-color = theme-config("myFeature.text", "default value")
  3. Read in templates (EJS under layout/):
    <% if (theme.myFeature.enable) { %> <div><%= theme.myFeature.text %></div> <% } %>
  4. Release: after config changes run tools/cicd.sh -r "feature" to bump the version (config counts as code-side changes; see release flow selection in the Deployment chapter)

Output: the built page contains <div>Hello</div>; the second argument of theme-config is the fallback used when the key is missing.

4.3 All tunable keys

OptionLocationPurpose
userConfig/_config.tmp.ymlrepothe single authoritative template (CI copies it to the theme config)
themes/matery/_config.ymltheme submodulebuild artifact, do not edit by hand
theme-config("a.b", "default")Stylusread config, falling back to the default when the key is missing
theme.a.bEJSread the config object directly

4.4 Boundaries & conflicts

  • The tools/cicd.sh build pipeline injects config (sed-replaces placeholders in the userConfig/_config.tmp.yml template), processes image URLs (imgurl.sh --weserv2githubpage), and generates the PWA Service Worker (userConfig/sw.tmp.js → source/sw.js); grep before editing the template to confirm key names aren’t already used by build scripts.
  • The theme config is 3000+ lines and is overwritten wholesale in CI; a local hexo server reads whatever is currently in themes/matery/_config.yml — when the two disagree, the template wins.

4.5 Summary

  • Changing config: edit only userConfig/_config.tmp.yml
  • Reading config: theme-config() in Stylus, theme.xxx in EJS
  • Verify: after building, grep the theme config for the key
  • Release: config is code-side, use -r

5. Custom File Config Keys (custom_file_path / custom_js / custom_css)

Purpose: specify custom JS/CSS file paths directly in the theme config and have them auto-loaded site-wide — less work than §1 method 1 (in-page references) and simpler than §2 inject points; ideal for “just add a script/style”.

Learning path: How to enable → Common options → All tunable keys → Boundaries & conflicts

5.1 How to enable

Effect: files listed in the config are pulled into every page’s <head> (CSS) and before </body> (JS) automatically — effective on all pages, with no per-page tags.

Corresponding config (theme config):

# Specify custom .js file paths, list supported; paths are relative to the source directory
# e.g. /js/custom.js corresponds to source/js/custom.js
custom_js:
  - /js/custom.js

# Specify custom .css file paths, same usage as custom_js
custom_css:
  - /css/custom.css

# Custom file path (Next theme inject reference, empty in this project)
custom_file_path:

Output: after building, every page HTML contains the corresponding <script src="/js/custom.js"> / <link rel="stylesheet" href="/css/custom.css">, generated by scripts.ejs / css.ejs.

5.2 Common options

① Load multiple files in order

Effect: entries earlier in the list load first, so later files can depend on earlier ones (e.g. a jQuery compatibility shim first, business scripts after).

Corresponding config:

custom_js:
  - /js/vendor.js
  - /js/app.js

② Add CSS only

Effect: injects styles only, producing no extra JS request.

Corresponding config:

custom_css:
  - /css/custom.css

③ Keep custom_file_path empty

Effect: this project doesn’t use that key; when empty the build injects nothing extra, identical to not configuring it.

Corresponding config:

custom_file_path:

5.3 All tunable keys

KeyTypeDefaultValues / rangePurpose
custom_jsarrayemptylist of .js paths relative to source/load custom JS site-wide
custom_cssarrayemptylist of .css paths relative to source/load custom CSS site-wide
custom_file_pathanyemptyunused in this projectNext theme inject reference; leave empty

Notes:

  • Place files under source/js/, source/css/ etc.; they are copied as-is to the matching public/ path at build time
  • custom_js/custom_css are lists — configure multiple files, loaded in order
  • custom_file_path references Next theme default-injects.js; unused in this project, leave empty

5.4 Boundaries & conflicts

  • Paths are rooted at source/ (/js/custom.js → source/js/custom.js); a wrong path doesn’t fail the build but 404s on the page.
  • Registering the same file through §2 inject points loads it twice; so does an additional in-page reference.
  • The config key lives in userConfig/_config.tmp.yml; editing the theme _config.yml directly gets overwritten on the next build (see §4).

5.5 Summary

  • Minimum viable: custom_css: [/css/custom.css] or custom_js: [/js/custom.js]
  • Multiple files: list order is load order
  • Conditional loading / fixed position: switch to inject points (§2)
  • 404: check whether the path is relative to source/

6. Encryption Architecture (HBE v4)

Purpose: theme-built-in encryption (developed in-house 2026-08-09, based on hexo-blog-encrypt v4, wire format format: '4'), covering three encryption surfaces.

Learning path: How to enable → Common options → All tunable keys → Boundaries & conflicts

6.1 How to enable

Effect: opening an encrypted post hides the body behind a password prompt first; entering the correct password decrypts and shows it, a wrong password shows the error message.

Corresponding config (post front-matter + theme config):

# post front-matter
password: "your password"
# theme config encrypt section
encrypt:
  enable: true

Output: that post’s HTML holds AES-256-GCM ciphertext (no plaintext body); the front end decrypts with WebCrypto and then renders.

6.2 Common options

The three encryption surfaces:

#SurfaceDeclared byImplementation
aEntire postfront-matter password, or post tag matching encrypt.tagsscripts/encrypt/index.js after_post_render filter (priority 1000)
bInline snippetMarkdown {% encrypt password "prompt title" "content summary" %}…{% endencrypt %}scripts/tags/encrypt-tag.js stages + same filter (priority 2000) second pass
cWiki / gallery pageWiki sidebar data encrypt_password (see the Multilingual & Wiki System page §10); gallery uses the encryptHtml helperlayout/wiki.ejs, gallery.ejs

① Encrypt a whole post

Effect: only that post asks for a password; other posts open normally.

Corresponding config: front-matter password (see §6.1).

② Encrypt in bulk by tag

Effect: tagging a post with the configured tag encrypts it automatically — no per-post password.

Corresponding config:

encrypt:
  tags:
    - name: Private
      password: "your password"

③ Skip the password after refresh (autoSave)

Effect: refreshing/going back in the same browser skips the prompt and decrypts directly; another browser or clearing localStorage requires the password again.

Corresponding config:

encrypt:
  autoSave: true

④ Stable salt across clean builds (stableSalt)

Effect: the same post keeps the same salt on rebuild, so cached derived keys stay valid; with it off, the salt changes on every build.

Corresponding config:

encrypt:
  stableSalt: true

6.3 All tunable keys

KeyDescription
encrypt.enableMaster encryption switch
encrypt.abstractPlaceholder summary for encrypted post listings (also overrides excerpt to prevent content leakage)
encrypt.message / encrypt.wrong_pass_messagePrompt / wrong-password message
encrypt.tags{name, password} list; posts whose tags match are encrypted
encrypt.autoSaveWrites the derived key to localStorage, skipping the password on refresh (off by default)
encrypt.stableSaltStable PBKDF2 salt across clean builds (default false)
encrypt.kdf.iterationsPBKDF2 iteration count; floor 100000, recommended ≥ 600000, default 250000

Post front-matter can override password/abstract/message/theme/wrong_pass_message/silent/autoSave/stableSalt/kdf; the template userConfig/_config.tmp.yml is authoritative.

6.4 Boundaries & conflicts

Encryption mechanism (server-side scripts/encrypt/crypto.js and client-side source/libs/hbe/hbe-bundle.js (WebCrypto) must use matching parameters):

  • Key derivation: PBKDF2-SHA256, iteration count set by encrypt.kdf.iterations
  • Symmetric encryption: AES-256-GCM; 32-byte random salt + 12-byte random nonce; ciphertext = ciphertext || authTag(16B)
  • With stableSalt: true the salt is derived from the post permalink (stableSaltFromPermalink), so repeated builds of the same post keep a stable salt and cached decryptions stay valid; the nonce remains random each time to avoid nonce reuse

Multi-container storageKey: encrypted snippets carry a data-storage-key attribute; hbe-bundle.js uses storageKey || location.pathname as the localStorage cache key (prefix hbe.v4.), so multiple encrypted containers on the same page don’t collide — snippets use segment.<path>#<id>, wiki uses wiki.<name>, and whole-post leaves it empty (falling back to the page path).

Search engine exclusion (none of the three engines index encrypted content): the local search scripts/generators/local-search.js skips post.encrypt === true; Algolia scripts/generators/algolia-search.js returns null for record.encrypt === true; Pagefind is excluded by layout/_partial/post/post-detail.ejs which omits data-pagefind-body when page.encrypt is true.

6.5 Summary

  • Minimum viable: encrypt.enable: true + front-matter password
  • Hide just one block: use the encrypt tag, don’t encrypt the whole post
  • Encrypt a whole section: encrypt_password in the Wiki sidebar data
  • Password in plaintext: HBE v4 takes plaintext directly, no SHA256 pre-hashing needed

Appendix: Customization Quick Reference

NeedApproachFile location
Per-page script/style<link>/<script> in Markdownsource/js/, source/css/
Site-wide script/styleinject_point injectionthemes/matery/scripts/filters/
New shortcodetag pluginthemes/matery/scripts/tags/
Theme config itemtemplate key + read in Stylus/EJSuserConfig/_config.tmp.yml
Global HTML fragmentinjection points or _partial/ templatesconfig or themes/matery/layout/_partial/
Encryption (HBE v4)three surfaces: whole post / snippet / Wikithemes/matery/scripts/encrypt/
Comments
Data Loading...