두 번째 주는 아예 처음 접하는 내용이 많았다.
이번 프로젝트는 ajax와 api로 데이터를 불러와서 html 형태로 append를 하게 되면 빈 화면이 잠시 보이다가 원하는 화면이 뜨는 문제가 있었다.
이 경우 서버에서 requests를 통해 외부 api에서 먼저 데이터를 받아 렌더링 할 때 변수로 넘겨준 후 jinja2를 이용해 클라이언트에서 로딩 없이 바로 보이게 할 수 있다.
@app.route('/detail/<keyword>')
def detail(keyword):
r = requests.get(f"https://owlbot.info/api/v4/dictionary/{keyword}", headers={"Authorization": "Token [토큰]"})
if r.status_code != 200:
return redirect(url_for("main", msg="없는 단어입니다"))
result = r.json()
return render_template("detail.html", word=keyword, result=result)
<script>
# 스크립트 내 변수도 가능하고
let word = '{{ word }}'
</script>
<body>
# html에 집어넣는 것도 가능하다
<h1 id="word" style="display: inline;">{{ result.word }}</h1>
</body>
{% if status=="old" %}
표기할 html
{% else %}
else 도 가능
{% endif %}
{% for elm in list %}
표기할 html; elm이 여러개라면, append처럼 내용이 계속 붙는다
{{ loop.index0 }} 로 elm의 순번을 가져올 수 있다. 0 빼면 1부터 시작
{% endfor %}
여러 페이지에서 중복되는 CSS는 static 폴더 내 css 파일에 작성한 후 각 페이지에서 불러오면 된다
<link href='{{ url_for("static", filename="mystyle.css") }}' rel="stylesheet">
$(`#id_${index}`).addClass("클래스명")
$(`#id_${index}`).removeClass("클래스명")
# 주소가 /detail/word?status_give=new 라면
@app.route('/detail/<keyword>')
def detail(keyword):
status_receive = request.args.get("status_give")
>> keyword = word, status_receive = new