테스트 사이트 - 개발 중인 베타 버전입니다

Python Flask Tutorial #2 - Templates

· 5년 전 · 919

https://youtu.be/QnDWIZuWYW0?list=PL-osiE80TeTs4UjLw5MM6OjgkjFeUxCYH

 

Flask에서 Templates로 웹 페이지 구성에 대한 설명입니다.

 

mkdir templates 

그안에 home.html 만들고..

 

vscode에서 html:5 로 하면 HTML 골격이 나오죠..

 

flaskblog.py에서 render_template를 import하고

return render_template('home.html') 을 하면 템플리트 웹 페이지가 표시됩니다.

 

about 페이지도 같은 방식으로 만드세요.. about.html

 

다음으로는 template에 데이타를 넘겨주는 방법입니다.

 

posts = [

    {

        'authos': 'Corey Schafer',

        'title': 'Blog Post 1',

        'content': 'First post content',

        'date_posted': 'April 20, 2018'

    },

    {

        'authos': 'Jane Doe',

        'title': 'Blog Post 2',

        'content': 'Second post content',

        'date_posted': 'April 21, 2018'

    }

]

 

https://jinja.palletsprojects.com/en/2.10.x/templates/

control 문은 {%  %} 으로 쓰고 변수는 {{ }} 이렇게 사용합니다.

render_template에 Post에 대한 것을 아래와 같이 넘겨주고

return render_template('home.html', posts=posts)

 

home.html에서

<body>

    {% for post in posts %}

        <h1>{{ post.title }}</h1>

        <p>By {{ post.author}} on {{ post.date_posted}}</p>

        <p>{{ post.content }}</p>

    {% endfor %}

</body>

 

와 같이 받아 주면 됩니다.

 

home.html 과 about.html의 html 코드가 겹치는 부분은 layout.html으로 보내고

 

다른 부분만 아래처럼 처리함.

 

{% extends "layout.html" %}

{% block content %}

{% endblock content %}

 

다음으로 꾸미기인데 bootstrap을 최신것을 Copy & Paste로...

 

snippet 디렉토리에 미리 사용할 코드블럭을 만들어 두었다가 Copy & Paste로 하네요.

 

https://github.com/CoreyMSchafer/code_snippets/tree/master/Python/Flask_Blog/snippets

 

CSS 파일은

 

static 디렉토리 아래에 놓고, url_for를 사용해서 읽어옴.

 

<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='main.css') }}">

 

1808292852_1575478435.9773.png

댓글 작성

댓글을 작성하시려면 로그인이 필요합니다.

로그인하기

게시글 목록

번호 제목
186
185
183
182
181
180
179
178
177
176
175
174
173
171
170
169
168
167
166
165
164
162
161
160
159
158
157
156
155
154