728x90
반응형

환경

  • Python 3.6
  • Django 2.1.1
  • VueJS Single Application

 

요약

Django 서버쪽에서 뷰 페이지(프론트)를 렌더링을 할때 특정 파라미터를 전달을 하여 사용하고싶은데 Django Template Code는 SPA의 어플리케이션 (Vue, React, Angular)의 템플릿 코드랑 겹쳐서 사용을 하기 애매하다. 

예) {{ test = context.test }}

 

대응

서버쪽에서 context 에서 특정 파라미터를 설정하여 보내면 view.py에서 설정한 HTML 페이지 (정적인 페이지로 프론트에서 SPA 어플리케이션이 렌더링을 하기 전 단계이다. 프론트 페이지 렌더링 하기 전단계)

에서 javascript 전역 변수에 담아 사용하는 방법이다.

 

    • view.py 코드
def index():
  context_params = {
    'test' : 'Hello Vue'
  }
  context = {'django_template_parameters': json.dumps(context_params)}
  return TemplateResponse(request, 'index.html', context=context)
 
    • index.html 페이지
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>TEST PAGE</title>
</head>
<body>
<div id="app"></div>
<script>
    try {
        var djangoTemplateParams = "{{ django_template_parameters }}".replace(/&quot;/g, "\"");
        window.djangoTemplateParams = JSON.parse(djangoTemplateParams);
    } catch (e) {
        // console.error(e);
    }

</script>
</body>
</html>
    • vue 페이지 App.vue
<template>
	<app></app>
</template>
<script>
  export default {
  name: "app",
  data() {
    return {
      // 서버에서 설정된 JSON 데이터 중 test 파라미터 사용
	  test : window.djangoTemplateParams.test 
	}
  }
</script>

 

728x90
반응형