본문 바로가기

WEB/Bootstrap

[Web][Bootstrap][Python][Flask]예시template 을 이용해서 flask에연결해보기-2.

목표

  • 여러 페이지를 만들고, 반응형 내비게이션을 사용한다.
  • 포스트 페이지를 동적으로 만들고 페이지를 수정한다.

참조할 templatehttps://startbootstrap.com/theme/clean-blog

 

Clean Blog - Bootstrap Blog Theme - Start Bootstrap

Like our free products? Our pro products are even better! Go Pro Today!

startbootstrap.com

 

1. flask을 이용해서 잘 연결하기

 

이것은 지난 포스팅을 참고하자

2022.05.27 - [WEB/Bootstrap] - [Web][Bootstrap][Python][Flask]예시template 을 이용해서 flask에연결해보기

 

[Web][Bootstrap][Python][Flask]예시template 을 이용해서 flask에연결해보기

오늘의 목표 flask에 다운받을 리소스들을 잘 연결해보자 오늘의 도구 bootstrap/flask/startbootstrap 참조할 멋있는 template : https://startbootstrap.com/theme/grayscale [Grayscale - Free One Page Bootst..

tae-05-yu.tistory.com

 

2. 여러 페이지를 만들기

html파일 안에 nav을 보면 여러 페이지의 링크가 있다.

                  <ul class="navbar-nav ms-auto py-4 py-lg-0">
                        <li class="nav-item"><a class="nav-link px-lg-3 py-3 py-lg-4" href="index.html">Home</a></li>
                        <li class="nav-item"><a class="nav-link px-lg-3 py-3 py-lg-4" href="about.html">About</a></li>
                        <li class="nav-item"><a class="nav-link px-lg-3 py-3 py-lg-4" href="post.html">Sample Post</a></li>
                        <li class="nav-item"><a class="nav-link px-lg-3 py-3 py-lg-4" href="contact.html">Contact</a></li>
                    </ul>

여기에 저장된 링크를 살펴보자 '파일.html'이렇게 연결되어있다.

저 링크를 누를 때마다 url주소/index.html 이렇게 주소가 변경된다.

그렇다면 저 flask에서 서버를 불러오기 위해서는

@app.route('/index.html')
def home_page():
    return render_template('index.html')

와 같이 route('/index.html') 이라 써야한다. 만일 저기에 href="abc"였다면 .route('/abc')라 해야한다

이와 같은 라우트 연결 함수를 contact about post 마저  만들어 내고 실행을 누르면 로컬서버에서 다른 페이지로 연결이 가능하다.

 

3. 새로운 포스트페이지 만들기

하지만 새로운 함수를 만들고 난 후의 페이지에서 다시 다른 페이지로 넘어갈 때 오류가 난다.

그럴 때는 url_for('함수')을 사용한다. 밑에 마지막 함수 처럼 말이다.

@app.route('/post.html')
def post_page():
    return render_template("post.html")

@app.route('/about.html')
def about_page():
    return render_template("about.html")
    
@app.route('/post/<int:index>')
def show_post(index):
    requested_post=None
    for blog_post in posts:
        if blog_post["id"] == index :
            requested_post=blog_post
    return render_template("post.html", post=requested_post)

post페이지에서 다른 페이지를 넘어가고자 하면 주소창이 로컬/post/index.html 이런식으로 바뀌므로 없는 페이지를 찾게된다.

<a class="nav-link" href="{{ url_for('contact_page') }}">contact</a>

와 같이 {{url_for(함수)}}를 사용하는 것이 편하다.

 

함수에 쓰인 posts은 받아온 api 의 json형식안에 데이터들이다.