How I added multiple languages to my blog

Поділитися
Вставка
  • Опубліковано 15 жов 2024
  • Read directly: claytonhickey....
    How I added multiple languages to my blog
    I like to study other languages, currently Japanese. So when I was talking to Hayden about improving our blogs, I decided I would just make it multilingual for fun. Now, at the bottom of the page, there are buttons to switch the language instantly:
    "Switch Language: [English] [日本語]"
    I'm not fluent in Japanese yet, so there will probably be mistakes.
    I saw a bunch of Stack Overflow posts that said that the only acceptable way to support multiple languages on a website is to send a different version of a page server-side depending on the user's preferred language. It is said that this reduces the amount of data the user has to download, and I agree. However, doing that would require me to increase the complexity of this site by something like 20 times. So, I don't want to.
    I love web components because they basically just add features to HTML, which is like 99% of what I want web frameworks like React to do. So, I created a web component with the tag name "ml-s" in 77 lines of code. Each of its children have a "lang" attribute to indicate the language of its contents. Depending on the user's browser-defined preferred languages and the override buttons in the footer, it chooses which of its children is the best and replaces itself with the best child and backs up the children. If the language preferences change, it replaces again based on the backed-up children.
    The HTML for this page's header
    I love this solution because it's super simple and effective for normal viewing. For RSS, it's a little more complicated. Luckily, HTML is structured data, so for the different English/Japanese RSS feeds, I just parse the HTML page, title, and description using Lambda Soup (aantron.github...) , extract the language from each ml-s element, convert it back into HTML text.
    It's also a little complicated for the page title since HTML can only have text in the title, no HTML tags. So, I use a hidden element at the top of the body and everytime it changes, it updates the title with the text representation of itself. Still less complicated than React (dev.to/rohitni...) 🤭.
    Thank you for reading, I hope the simplicity inspires you as it does me.
    a copy of the current relevant code (/blog/how-I-added-multiple-languages-to-my-blog/multilingual.js)

КОМЕНТАРІ •