flask와 html 간의 변수 전달

semi·2020년 11월 19일
1

Web

목록 보기
2/2

html에서 backend로 변수 전달

  • index.html
<form action="\post" method="post" class="input-form">
    <textarea type="text" name='id_name' value="tmp tmp tmp" class="input-text"></textarea>
    <input type="submit" value="submit" class="input-btn">
</form>

form태그를 이용하여 post 방식으로 전달한다.
value에 있는 tmp tmp tmp는 아무것도 작성하지 않았을 당시 초기값이다.

  • app.py
@app.route('/post', methods=['GET','POST'])
def post():
    if request.method == 'POST':
        value = request.form['id_name']
        value = str(value)
        print(value)
    return render_template('post.html')

post 방식으로 request가 들어온 경우, id_name의 name을 가진 form의 value를 전달 받는다.

backend에서 html로 변수 전달

  • app.py
@app.route('/tmp', methods=['GET','POST'])
def tmp():
    value = 'hello, world'
    return render_template('tmp.html', value = value)

tmp 함수에서 value를 tmp.html에 전달한다.

  • tmp.html
<div class="print"> {{value}}를 전달받았습니다. </div>

결과적으로 화면에는 "hello, world를 전달받았습니다."가 출력된다.

0개의 댓글