ในภาษา Python นั้นมี flask เป็นตัวที่ใช้สำหรับการสร้างเว็บไซต์ ซึ่งสามารถใช้จัดการหน้าเว็บไซต์ และในตัว flask นั้นก็จะมีตัวฟังก์ชั่นที่มาชื่อ url_for ใช้สำหรับการ route ไปยังฟังก์ชั่นที่อยู่ในโค้ดโปรแกรมของเรา ฟังก์ชั่นจะคล้ายๆ กับฟังก์ชั่น render_template มาตัวอย่างดังนี้
โค้ด: เลือกทั้งหมด
from flask import Flask,url_for ,redirect
app=Flask(__name__)
@app.route('/')
def index():
return redirect(url_for('test2'))
@app.route('/test2')
def test():
return "Hello test"
@app.route('/test3')
def test2():
return "Hello test2"
if __name__=='__main__':
app.run()
โค้ด: เลือกทั้งหมด
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<a class="btn" href="{{url_for('test')}}">test</a><br>
<a class="btn" href="{{url_for('test2')}}">test2</a>
</body>
</html>
โค้ด: เลือกทั้งหมด
from flask import Flask,render_template
app=Flask(__name__)
@app.route('/')
def index():
return render_template('home.html')
@app.route('/test2')
def test():
return "Hello test"
@app.route('/test3')
def test2():
return "Hello test2"
if __name__=='__main__':
app.run()
ถ้าเราคลิกที่ลิ้ง test คลิกที่ลิ้ง test2 อ้างอิง
http://flask.pocoo.org/docs/1.0/api/
https://www.stackoverflow.com/questions/7478366/create-dynamic-urls-in-flask-with-url-for
http://screenth.blogspot.com/2017/07/flask-hello-world.html