depth가 깊은 프로젝트를 진행 중이다 보니 ejs 파일끼리 연결하는데 어려움을 겪고 있다. 그 중 제일 오랜시간이 걸렸던 게시판 글 목록에서 하나의 글 상세페이지로 이동하는 부분을 연결하는 방법에 대해 기록으로 남기고자 한다.
컬렉션 - 문서 - 컬렉션 - 문서 - 필드
로 계속 들어가는 구조이다.문서 - 필드
강조된 부분으로 각 동호회 게시판 안의 게시판 글 목록 중 하나의 글을 선택하면 글 상세보기를 하는 부분이다.<%-include("../clubNav.ejs")%>
<div class="row my-2">
<div class="col">
<h3 class="text-center mt-4 mb-2">게시글</h3>
<div class="text-end">
<button class="btn btn-primary btn-sm" id="btn-write">글쓰기</button>
</div>
<div id="boards"></div>
<div class="text-center my-3" id="btn-group" style="display: none">
<button class="btn btn-primary btn-sm" id="btn-prev">이전</button>
<span class="px-2" id="span-page">1</span>
<button class="btn btn-primary btn-sm" id="btn-next">다음</button>
</div>
</div>
</div>
<script id="temp" type="text/x-handlebars-template">
{{#each .}}
<div class="card my-2" style="font-size:0.8rem">
<div class="card-body">
<a href="/clubMain/{{category}}/{{id}}/{{rid}}"><h5>{{ title }}</h5></a>
<div class="ellipsis2">{{ body }}</div>
</div>
<div class="card-footer">
<span>Posted on {{ date }} by {{ email }}</span>
</span>
</div>
</div>
{{/each}}
</script>
<script type="module">
import { app } from "/javascripts/firebase.js";
import { getFirestore, collection, setDoc } from 'https://www.gstatic.com/firebasejs/9.22.1/firebase-firestore.js';
import { query, where, getDocs, orderBy, doc, deleteDoc } from "https://www.gstatic.com/firebasejs/9.22.1/firebase-firestore.js";
const db = getFirestore(app);
const category = "<%=id%>";
const clubId = "<%=id2%>";
console.log(category);
console.log(clubId);
let page = 1;
getList();
$("#btn-next").on("click", function(){
page++;
getList();
})
$("#btn-prev").on("click", function(){
page--;
getList();
})
async function getList(){
const q = query(collection(db, `club-category-${category}`, clubId, 'board'), orderBy('date', 'desc'));
const snapshot = await getDocs(q);
let rows = [];
snapshot.docs.forEach(async (row, index) => {
console.log(index);
//한 페이지에 몇 개씩 보여줄까?
let size = 3;
//마지막 페이지의 숫자를 구하는 공식은? - 총 레코드 숫자
let last = Math.ceil(snapshot.docs.length/size);
//시작 페이지의 숫자 구하기
let start = (page-1)*size;
let end = (page*size)-1;
if(index >= start && index <= end){
console.log("row id =====> " + row.id); rows.push({rid:row.id,category:category,id:clubId,...row.data()});
console.log(rows); //원본에 id키를 갖는 값이 들어갔나?
let temp = Handlebars.compile($('#temp').html());
$('#boards').html(temp(rows));
/* 페이징 처리 UI 추가 */
if(snapshot.docs.length > 0){ //조회된 결과가 있어?
$("#btn-group").show();
}
$("#span-page").html(page+"/"+last)
//네가 첫 페이지니? 응 - 이전버튼은 비활성화
if(page == 1) $("#btn-prev").attr("disabled", true);
else $("#btn-prev").attr("disabled", false);
//네가 마지막 페이지니?
if(page == last) $("#btn-next").attr("disabled", true);
else $("#btn-next").attr("disabled", false);
/* 페이징 처리 UI 추가 */
}//end of if
});//end of forEach
}//end of getList
//개발자 센터 > application > storage > Local storage
const email = localStorage.getItem("email");
$("#btn-write").on("click", () => {
//로그인을 해야만 글쓰기 권한이 있다
//너 로그인 했니? 너 email값 쥐고 있어? - 어디에? localStorage
if(email){
location.href = "/clubMain/<%=id%>/<%=id2%>/write";
}
//나 로그인 안했어. 하고 와
else {
location.href = "/login";
}
})
</script>
위 코드에서 핸들바스 부분 중 <a href="/clubMain/{{category}}/{{id}}/{{rid}}"><h5>{{ title }}</h5></a>
이 곳에서 {{}} 안에 값을 넣어줘야 한다.
하지만 rows.push({id:row.id,...row.data()});
이 상태로만 두다보니 값이 들어가지 않아 홈페이지 url이 http://localhost:9999/clubMain///
비어있어 404오류가 계속 발생하였다.
이 문제를 해결하기 위해서는 spread 연산자를 사용하여 핸들바스에 넣을 아이디 값을 push 해야 한다.
rows.push({rid:row.id,category:category,id:clubId,...row.data()});
이렇게 값을 넣어야 핸들바스에 값이 제대로 전달되어 홈페이지 url도 제대로 출력된다.
http://localhost:9999/clubMain/study/gJq0PmnFczz0rhY7VuAx/nLrZOCxOmENqpDQ4Q959
핸들바스를 이용하면 꼭 push를 통해 값을 넣어주어야 한다. 스프레드 연산자를 좀 더 익숙하게 쓸 수 있도록 많은 연습이 필요하다.