본문 바로가기
PRACTICE/Basic

[Flask] jinja template 활용하여 static 폴더의 자료 가져오기

by 1005 2020. 9. 24.

 

 

< 폴더 경로 >

 

 

< app.py >

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
 
# jinja 탬플릿을 활용하여 static 폴더의 자료를 가져오는 예제. 
 
from flask import Flask 
from flask import render_template
 
app = Flask(__name__)
 
@app.route('/')
def index():
   return render_template('index.html')
 
if __name__ == '__main__':
   app.run(host='0.0.0.0', port = 80, debug = True)

 

< style.css >

 

 

 

< index.html >

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css" href="{{ url_for('static',filename='./css/style.css') }}">
    <title>static폴더 사용하기</title>
</head>
<body>
    <p>url_for를 통해서 css적용하기</p><br>
    <h3>url_for를 통해서 img 출력하기</h3>
    <img src="{{ url_for('static',filename='Quokka.jpg') }}">
</body>
</html>

 

python이 정상적으로 실행되는 것을 확인한 후에

css에서 <p> 태그의 color 값을 yellow에서 royalblue로 바꿨다.

현재 페이지를 새로고침(F5)하면 css값이 변경될 줄 알았는데 그렇지 않았고

캐시된 콘텐츠를 무시하고 현재 페이지 새로고침(ctrl+ shift + r )을 사용하니 변경된 값으로 화면이 출력되었다. 

 

 

 

 

새로고침 버튼 없이

python을 실행할 때마다 변경된 적용값을 출력하고 싶으면

css값이 변수에 저장되어 출력될 수 있게 코드를 작성하면 된다. 

 

1
2
3
4
5
6
7
<head>
  <!-- 초기버전 -->    
  <!-- <link rel="stylesheet" type="text/css" href="{{ url_for('static',filename='./css/style.css') }}"> -->
    
  <!-- 변수로 적용한 버전 -->
  <link rel="stylesheet" type="text/css" href="/static/css/style.css?{{range(1,51) | random}}">
</head>

 

 

 

댓글