Skip to content

Latest commit

 

History

History
171 lines (138 loc) · 4.99 KB

2_4_7.i18n.md

File metadata and controls

171 lines (138 loc) · 4.99 KB

Node.js와 Express를 활용하여 구축한 게시판에 다국어 지원 기능을 추가하려면, 국제화(i18n) 라이브러리를 사용하여 다양한 언어로 콘텐츠를 제공할 수 있습니다. 이 과정에서는 i18n 모듈을 활용하여 다국어 지원을 구현하는 방법을 단계별로 안내하겠습니다.

1. 필요한 모듈 설치

먼저, 프로젝트 디렉토리에서 i18n 모듈과 cookie-parser를 설치합니다. cookie-parser는 사용자의 언어 설정을 쿠키로 관리하기 위해 필요합니다.

npm install i18n cookie-parser

2. i18n 설정 파일 생성

프로젝트 루트 디렉토리에 i18n.js 파일을 생성하고, 다음과 같이 설정합니다. 이 설정은 지원할 언어(locales), 기본 언어(defaultLocale), 번역 파일이 저장될 디렉토리(directory), 그리고 언어를 저장할 쿠키 이름(cookie)을 정의합니다.

const i18n = require('i18n');
const path = require('path');

i18n.configure({
  locales: ['ko', 'en'], // 지원할 언어 코드
  defaultLocale: 'ko',   // 기본 언어 설정
  cookie: 'lang',        // 언어를 저장할 쿠키 이름
  directory: path.join(__dirname, 'locales') // 번역 파일 디렉토리
});

module.exports = i18n;

3. server.js 파일 수정

server.js 파일에서 i18ncookie-parser를 불러오고, Express 애플리케이션에 해당 미들웨어를 추가합니다.

const express = require('express');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser'); // 추가
const i18n = require('./i18n'); // 추가
const app = express();
const port = 3000;

// EJS를 뷰 엔진으로 설정
app.set('view engine', 'ejs');

// 미들웨어 설정
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser()); // 추가
app.use(i18n.init); // 추가

// 게시글 데이터를 저장할 배열
let posts = [];

// 언어 변경 라우트 추가
app.get('/lang/:locale', (req, res) => {
  res.cookie('lang', req.params.locale, { maxAge: 900000, httpOnly: true });
  res.redirect('back');
});

// 루트 경로에서 게시글 목록 표시
app.get('/', (req, res) => {
  res.render('index', { posts });
});

// 게시글 작성 폼 표시
app.get('/new', (req, res) => {
  res.render('new');
});

// 게시글 작성 처리
app.post('/create', (req, res) => {
  const { title, content } = req.body;
  const newPost = { title, content, date: new Date().toLocaleString() };
  posts.push(newPost);
  res.redirect('/');
});

// 서버 실행
app.listen(port, () => {
  console.log(`서버가 http://localhost:${port} 에서 실행 중입니다.`);
});

4. 번역 파일 생성

i18n.js 파일에서 지정한 locales 디렉토리에 언어별 JSON 파일을 생성합니다. 예를 들어, ko.jsonen.json 파일을 생성하고, 각 파일에 번역 키와 값을 정의합니다.

  • locales/ko.json:

    {
      "title": "게시판",
      "new_post": "새 글 작성",
      "submit": "제출",
      "post_title": "제목",
      "post_content": "내용"
    }
  • locales/en.json:

    {
      "title": "Bulletin Board",
      "new_post": "New Post",
      "submit": "Submit",
      "post_title": "Title",
      "post_content": "Content"
    }

5. EJS 템플릿 수정

EJS 템플릿 파일에서 i18n__ 함수를 사용하여 번역 키를 호출합니다. 예를 들어, views/index.ejsviews/new.ejs 파일을 다음과 같이 수정합니다.

  • views/index.ejs:

    <!DOCTYPE html>
    <html lang="<%= i18n.getLocale() %>">
    <head>
      <meta charset="UTF-8">
      <title><%= __('title') %></title>
    </head>
    <body>
      <h1><%= __('title') %></h1>
      <a href="/new"><%= __('new_post') %></a>
      <ul>
        <% posts.forEach(post => { %>
          <li>
            <h2><%= post.title %></h2>
            <p><%= post.content %></p>
            <p><small><%= post.date %></small></p>
          </li>
        <% }) %>
      </ul>
      <footer>
        <a href="/lang/ko">한국어</a> | <a href="/lang/en">English</a>
      </footer>
    </body>
    </html>
  • views/new.ejs:

    <!DOCTYPE html>
    <html lang="<%= i18n.getLocale() %>">
    <head>
      <meta charset="UTF-8">
      <title><%= __('new_post') %></title>
    </head>
    <body>
      <h1><%= __('new_post') %></h1>
      <form action="/create" method="post">
        <label for="title"><%= __('post_title') %>:</label>
        <input type="text" id="title" name="title" required>
        <br>
        <label for="content"><%= __('post_content') %>:</label>
        <textarea id="content" name="content" required></textarea>
        <br>
        <button type="submit"><%= __('submit') %></button>
      </form>
      <footer>
        <a href="/lang/ko">한국어</a> | <a href="/lang/en">English</a>
      </footer>
    </body>
    </html>

6. 서버 실행 및 테스트

서버를 실행하고 브라우저에서 http://localhost:3000/에 접속하여 기본 언어(한국어)로 페이지가 표시되는지 확인합니다. 페이지 하단의