วิธีการทำเว็บไซต์ 2 ภาษา ในภาษา python
ในภาษา
Python สามารถเขียนเว็บไซต์ได้การ
flask framework ซึ่งเป็นตัวจัดการเว็บไซต์ของภาษา Python ส่วนมากเว็บไซต์ต่างๆ จะทำมาให้รองรับ 2 ภาษา และสำหรับคนที่กำลังหาวิธีการทำหรือตัวอย่างสามารถนำไปใช้หรือประยุกต์ได้ ส่วนวิธีขั้นตอน เป็นการใช้ไฟล์ config มาเก็บตัวแปรของทั้งสองภาษา แล้วให้ส่งไปยังหน้าไฟล์ HTML เพื่อแสดง จะต้องทำการเรียกใช้ library
configparser ของ Python เพื่อใช้ตัวแปรในไฟล์ config โดยวิธีการก็จะมีดังนี้
คำสั่งติดตั้ง flask และ configparser
และ
ขั้นตอนแรกให้ทำการ import flask และ configparser
โค้ด: เลือกทั้งหมด
from flask import Flask, render_template
import configparser
แล้วเรียกใช้ configparser เพื่อเรียกไฟล์ config
โค้ด: เลือกทั้งหมด
config = configparser.ConfigParser()
config.read('config.conf')
จากนั้นให้สร้างตัวแปรในไฟล์ config.conf
โค้ด: เลือกทั้งหมด
[TH]
str1=สวัสดี ไพธอน
str2=วันนี้วันอะไร
[EN]
str1=Hallo python
str2=What's today
ทำการกำหนดตัวแปรในไฟล์ python
โค้ด: เลือกทั้งหมด
from flask import Flask, render_template, request
import configparser
config = configparser.ConfigParser()
config.read('config.conf')
text_en=config['EN']
text_th=config['TH']
สร้าง app.route ขึ้นมา
โค้ด: เลือกทั้งหมด
@app.route('/')
def index():
return render_template('home.html')
จากนั้นให้รับค่า get ที่ส่งมาจากหน้า HTML เเล้วเช็ค ตัวแปร get นั้น
โค้ด: เลือกทั้งหมด
@app.route('/', methods=['GET'])
def index():
text = text_th
if request.values.get('lang') and request.values.get('lang') == 'en':
text=text_en
return render_template('home.html' , text=text)
คำสั่งหน้า python
โค้ด: เลือกทั้งหมด
from flask import Flask, render_template, request
import configparser
config = configparser.ConfigParser()
config.read('config.conf')
text_en=config['EN']
text_th=config['TH']
app = Flask(__name__)
@app.route('/', methods=['GET'])
def index():
text = text_th
if request.values.get('lang') and request.values.get('lang') == 'en':
text=text_en
return render_template('home.html' , text=text)
if __name__=='__main__':
app.run(debug=True)
คำสั่งหน้า HTML
โค้ด: เลือกทั้งหมด
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
ข้อความ : <span>{{text['str1']}}</span><br>
ข้อความ : <span>{{text['str2']}}</span><br>
<a href="?lang=th">ภาษาไทย</a>
<a href="?lang=en">ภาษาอังกฤษ</a>
</body>
</html>
ผลที่ได้
จะสังเกตได้ตัวแปร get เท่ากัน th
เมื่อตัวแปรเปลี่ยนเป็น en ข้อความก็เปลี่ยนภาษาอังกฤษ
เท่านี้ก็เป็นอันที่เรียบร้อย
อ้างอิง
https://www.mindphp.com/forums/viewtopic.php?p=161740#p161740
https://www.mindphp.com/บทเรียนออนไลน์/python-framework-flask/6442-flask-framework-html-css-python.html
https://www.mindphp.com/คู่มือ/73-คืออะไร/2417-python-คืออะไร.html