본문 바로가기

파이썬

[파이썬]flask에서 jinja를 통한 html작성하기

html을 여러개 작성하는 것 보다는 render_temple를 쓰자

render_template

html파일을 만들고 얘를 render_template로 가져오면 된다.

from flask import Flask, render_template


app = Flask(__name__)

#직접 파이썬에서 run메서드를 구현해서 할 수도 있다.

if __name__ == '__main__':
    app.run(debug = True)


@app.route('/')
def index():
    return render_template('index.html')
  • 이때 폴더명이 templates라는 것에서 가져온다. (다른거는 안됨)
  • render_template()안에 templates안에 있는 가져올 파일 이름

진자 표현식

{{}} 진자의 변수 표현하기

@app.route('/<item>')
def index(item):
    #apple = 'apple'
    return render_template('index.html', item = item) #템플릿에 전달될때 apple라는 변수를 전달

이상황에서 html에 {{item}}을 넣으면 item변수를 사용할 수 있다.

<html>
  <head>
    <title>
      New HTML Page
    </title>
  </head>
  <body>
    <h1>I am in templates folder {{item}}</h1>
  </body>
</html>

{% block main_body %}{% endblock %}

이경우는 부모에 이걸 달아놓으면 이부분은 자식에서 새로 정의 하겠다는 뜻이다.

{% extends "index.html" %}

{% block main_body %}

<p1>this is example of block </p1>
{% endblock %}

이렇게 하면 자식에만 정의되어서 부모는 실행되지 않고 자식에서만 실행된다.