TWIL_스파르타코딩 웹개발 플러스 2주차

Refler·2021년 10월 31일

두 번째 주는 아예 처음 접하는 내용이 많았다.

1 서버 사이드 렌더링

이번 프로젝트는 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)
  • jinja2로 넘겨준 변수 사용하기
  • <script>
    	# 스크립트 내 변수도 가능하고
    	let word = '{{ word }}'
    </script> 
    <body>
    	# html에 집어넣는 것도 가능하다
    	<h1 id="word" style="display: inline;">{{ result.word }}</h1>
    </body>

    2 jinja2: if/loop

  • 특정 조건이 있을 때만 아래 html을 표기하기
  • {% if status=="old" %}
    	표기할 html
    {% else %}
    	else 도 가능
    {% endif %}
  • loop은 파이썬 처럼 for를 이용
  • {% for elm in list %}
    	표기할 html; elm이 여러개라면, append처럼 내용이 계속 붙는다
        {{ loop.index0 }} 로 elm의 순번을 가져올 수 있다. 0 빼면 1부터 시작 
    {% endfor %}

    3 중복CSS 분리

    여러 페이지에서 중복되는 CSS는 static 폴더 내 css 파일에 작성한 후 각 페이지에서 불러오면 된다

    <link href='{{ url_for("static", filename="mystyle.css") }}' rel="stylesheet">

    4 기타

  • 자바스크립트로 클래스 추가/삭제
  • $(`#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
    profile
    이제 시작

    0개의 댓글