Bear Blog, But Multilingual
{lang: en}
I have used Bear Blog for more than a year. It is the best platform I have ever written on, even though I don't write much.
I speak 3 languages (and I am learning a 4th), and my blog is a bit of a mess. Sometimes I write in my mother tongue, sometimes in English, and often I want to write in Japanese.
Many times I wanted to keep this blog in one language, but I could not choose which one.
So I looked for a way to make Bear Blog show several languages in the same post. And not only languages: with this plugin, I can also write a TL;DR version.
Here is how to use it:
Shared text, always visible.
{lang: en}
English version...
{lang: vi}
Vietnamese version...
{lang: ja}
Japanese version...
{lang: en-x-tldr}
TL;DR version...
{/lang}
Shared text after the languages.
Note: leave a blank line before each {lang: ...} marker.
Some limits of the plugin:
- If you read the post through RSS or the email newsletter, you see all languages at once. Search engines also see the post with all languages mixed together.
- Readers who turn off JavaScript in their browser see the content of every language.
- The post title does not switch (it could, but I am lazy).
- Plugins that show reading time or a table of contents may show wrong results, unless they skip hidden blocks.
Copy the script below and paste it into your blog footer, as Herman explains here.
{lang: vi}
Tôi dùng Bear Blog được hơn 1 năm. Đây là platform tuyệt vời nhất tôi từng viết, dù tôi không viết gì nhiều.
Tôi có thể nói được 3 ngôn ngữ (và đang học thêm ngôn ngữ thứ 4), và blog của tôi khá lộn xộn. Đôi khi tôi viết bằng tiếng mẹ đẻ, đôi khi bằng tiếng Anh, cũng có nhiều khi tôi muốn viết bằng tiếng Nhật.
Nhiều lần tôi muốn thống nhất blog này về một ngôn ngữ, nhưng không biết chọn ngôn ngữ nào.
Vì thế tôi tìm cách để Bear Blog có thể hiển thị nhiều ngôn ngữ trong cùng một bài post. Thậm chí không chỉ ngôn ngữ: với plugin này, tôi có thể viết cả một phiên bản TL;DR.
Cách dùng như sau:
Shared text, always visible.
{lang: en}
English version...
{lang: vi}
Vietnamese version...
{lang: ja}
Japanese version...
{lang: en-x-tldr}
TL;DR version...
{/lang}
Shared text after the languages.
Lưu ý: để một dòng trống trước mỗi marker {lang: ...}.
Các bạn có thể copy script sau, dán vào footer của blog theo hướng dẫn của Herman tại đây.
{lang: en-x-tldr}
TL;DR: I write in 3 languages and could not pick one for this blog. So I made a Bear Blog plugin. You write one post in several languages (or a TL;DR, like this one), and readers switch with a button.
{/lang}
/*
Plugin name: Multi-language post
Description: Write a post in several languages and let readers switch between them. Start each language with a line like {lang: en}. End the last one with {/lang} if shared content follows.
Author: cuuthegioi
Author URI: https://blog.sonngo.dev
*/
(function() {
'use strict';
// --- Configuration ---
const LABELS = { en: 'English', vi: 'Tiếng Việt', ja: '日本語', 'en-x-tldr': 'TL;DR' }; // Unknown codes show as upper case
const DEFAULT_LANG = ''; // Empty: use the first language in the post
const STORAGE_KEY = 'multi-language-post';
// ---------------------
// Matches {lang: xx} or {/lang} at the start of a paragraph, alone on its line
const MARKER = /^\s*\{\s*(?:lang\s*:\s*([a-zA-Z]{2,3}(?:-[a-zA-Z0-9]+)*)|\/\s*lang)\s*\}[ \t]*(?:\r?\n|$)/;
// Markdown joins a marker and the next line into one paragraph, so strip the marker and keep the rest.
function readMarker(node) {
if (node.nodeType !== Node.ELEMENT_NODE || node.tagName !== 'P') return null;
const first = node.firstChild;
if (!first || first.nodeType !== Node.TEXT_NODE) return null;
const match = first.data.match(MARKER);
if (!match) return null;
first.data = first.data.slice(match[0].length);
if (first.data === '') first.remove();
if (node.firstChild && node.firstChild.nodeName === 'BR') node.firstChild.remove();
const isEmpty = node.textContent.trim() === '' && !node.querySelector('img, iframe, video, audio');
return { lang: match[1] ? match[1].toLowerCase() : null, rest: isEmpty ? null : node };
}
// Bear adds tags, the upvote form and scripts after the post body; a block must not swallow them.
function isBearChrome(node) {
if (node.nodeType !== Node.ELEMENT_NODE) return false;
return node.matches('p.tags, #upvote-form, script');
}
function readStoredLang() {
try { return localStorage.getItem(STORAGE_KEY); } catch (e) { return null; }
}
function storeLang(lang) {
try { localStorage.setItem(STORAGE_KEY, lang); } catch (e) { /* storage blocked */ }
}
function pickInitialLang(langs) {
const fromUrl = new URLSearchParams(window.location.search).get('lang');
const fromBrowser = (navigator.languages || [navigator.language]).map(function(l) {
return String(l).toLowerCase();
});
const candidates = [fromUrl, readStoredLang()]
.concat(fromBrowser)
.concat(fromBrowser.map(function(l) { return l.split('-')[0]; }))
.concat([DEFAULT_LANG]);
for (let i = 0; i < candidates.length; i++) {
const c = candidates[i] && candidates[i].toLowerCase();
if (c && langs.indexOf(c) !== -1) return c;
}
return langs[0];
}
document.addEventListener('DOMContentLoaded', function() {
const body = document.body.classList;
if (!body.contains('post') && !body.contains('page')) return;
const main = document.querySelector('main');
if (!main) return;
// 1. Group the nodes between markers into one wrapper per language
const blocks = {};
const langs = [];
let current = null;
let firstBlock = null;
Array.from(main.childNodes).forEach(function(node) {
if (isBearChrome(node)) { current = null; return; }
const marker = readMarker(node);
if (marker && marker.lang) {
const lang = marker.lang;
current = document.createElement('div');
current.className = 'lang-block';
current.lang = lang;
main.insertBefore(current, node);
if (!blocks[lang]) { blocks[lang] = []; langs.push(lang); }
blocks[lang].push(current);
if (!firstBlock) firstBlock = current;
if (marker.rest) current.appendChild(node); else node.remove();
return;
}
if (marker) {
current = null;
if (!marker.rest) node.remove();
return;
}
if (current) current.appendChild(node);
});
if (langs.length === 0) return;
// 2. Build the switcher
const switcher = document.createElement('nav');
switcher.className = 'lang-switcher';
switcher.setAttribute('aria-label', 'Language');
const buttons = {};
langs.forEach(function(lang) {
const btn = document.createElement('button');
btn.type = 'button';
btn.lang = lang;
btn.textContent = LABELS[lang] || lang.toUpperCase();
btn.addEventListener('click', function() { show(lang, true); });
buttons[lang] = btn;
switcher.appendChild(btn);
});
const style = document.createElement('style');
style.textContent =
'.lang-switcher{display:flex;flex-wrap:wrap;gap:.5em;margin:1em 0}' +
'.lang-switcher button{font:inherit;color:inherit;background:none;border:1px solid currentColor;border-radius:3px;padding:.1em .6em;opacity:.6}' +
'.lang-switcher button[aria-pressed="true"]{opacity:1;font-weight:bold}';
document.head.appendChild(style);
firstBlock.parentNode.insertBefore(switcher, firstBlock);
// 3. Show one language
function show(lang, fromClick) {
langs.forEach(function(l) {
blocks[l].forEach(function(block) { block.hidden = l !== lang; });
buttons[l].setAttribute('aria-pressed', String(l === lang));
});
document.documentElement.lang = lang;
if (fromClick) {
storeLang(lang);
const url = new URL(window.location.href);
url.searchParams.set('lang', lang);
history.replaceState(null, '', url);
}
}
show(pickInitialLang(langs), false);
});
})();
</script>