본문 바로가기
카테고리 없음

TIL-4

by 오우지 2021. 9. 16.

지금까지 서버와 프론트의 대화는 json data를 통해 이뤄졌지만 이번에는 jinja2라는 템플릿을 이용해 본다.

index.html에서 출력되는 문장에서 매번 다르게 출력이 나오게 하고 싶다면 프론트에 {{name}}을 넣고

서버단에서는 페이지를 넘겨주는 함수에

 

@app.route('/')
def main():
    myname = "Sparta"
    return render_template("index.html", name = myname)

이런식으로 넘겨주면 값을 출력할 수 있다.

 

-기억해야 할 것

html의 ID값을 javascript에서 부르려면 $("#definitions") 이렇게 적어줘야 한다.

 

jinja template을 사용하면 javascript에서 직접 ajax콜을 하지 않아도 서버단에서 받아와서 쏴줄 수 있다.

 

위와 같은 화면을 쏴주기 위해서 owl API를 사용하는데 이때 json통신을 통해 자료를 받아온다.

지금까지 json통신을 위해서 javascript를 이용해

 

function get_definitions() {
            $.ajax({
                type: "GET",
                url: `https://owlbot.info/api/v4/dictionary/${word}`,
                beforeSend: function (xhr) {
                    xhr.setRequestHeader("Authorization", "Token 0ee92a2de90415678ad90b8ee7abca13744282c8");
                },
                data: {},
                error: function (xhr, status, error) {
                    alert("에러 발생!");
                },
                success: function (response) {
                    console.log(response)
                    $("#word").text(response["word"])
                    if(response["pronunciation"] == null) {
                        $("#pronunciation").text("")
                    } else{
                        $("#pronunciation").text(`/${response["pronunciation"]}/`)
                    }
                    let definitions = response["definitions"]
                    $("#definitions").empty()
                    for(let i = 0; i < definitions.length; i++){
                        let definition = definitions[i]
                        let html_temp = ""
                        if(definition["example"]==null){
                            html_temp = `<div style="padding:10px">
                                            <i>${definition["type"]}</i>
                                            <br>${definition["definition"]}<br>
                                        </div>`
                        }
                        else {
                            html_temp = `<div style="padding:10px">
                                            <i>${definition["type"]}</i>
                                            <br>${definition["definition"]}<br>
                                            <span class="example">${definition["example"]}</span>
                                        </div>`
                        }
                        $("#definitions").append(html_temp)
                    }
                }
            })
        }

이런식으로 직접 받아온 값을 입력해줬는데 jinja를 이용하는 방법은 내일 공부해야겠다.

오늘 너무 피곤하다.