[JSP] jsp + javascript 사용 시 템플릿 리터럴(${}) 문제

Hayden·2025년 7월 2일
            const imageWrapper =
              `
                <div class="image-preview-wrapper" style="position: relative; display: inline-block; margin: 10px;">
                    <img src="${e.target.result}" alt="미리보기" style="width: 150px; height: 150px; object-fit: cover; border-radius: 8px; border: 2px solid #ddd;">
                    <button type="button" class="remove-image-btn" data-index="${index}
                            style="position: absolute; top: -5px; right: -5px; background: red; color: white; border: none; border-radius: 50%; width: 25px; height: 25px; cursor: pointer; font-size: 12px;">
                        ×
                    </button>
                </div>
                    `;

오류

jsp + javascript 사용할 때 javascript에서 백틱 안에서 템플릿 리터럴${}을 사용하면 jsp는 jsp의 EL의 ${}로 착각해서 미리 서버에서 처리하려 하기 때문에 js에서 데이터를 처리하지 못합니다.

해결 방법

${e.target.value}${}으로 한 번 더 감싸줍니다. ${'${e.target.value}'}

            const imageWrapper =
              `
                <div class="image-preview-wrapper" style="position: relative; display: inline-block; margin: 10px;">
                    <img src="${'${e.target.result}'}" alt="미리보기" style="width: 150px; height: 150px; object-fit: cover; border-radius: 8px; border: 2px solid #ddd;">
                    <button type="button" class="remove-image-btn" data-index="${'${index}'}"
                            style="position: absolute; top: -5px; right: -5px; background: red; color: white; border: none; border-radius: 50%; width: 25px; height: 25px; cursor: pointer; font-size: 12px;">
                        ×
                    </button>
                </div>
                    `;

또는 아래와 같이 문자열을 사용하여 연결해 줍니다.

const imageWrapper = 
  '<div class="image-preview-wrapper" style="position: relative; display: inline-block; margin: 10px;">' +
    '<img src="' + e.target.result + '" alt="미리보기" style="width: 150px; height: 150px; object-fit: cover; border-radius: 8px; border: 2px solid #ddd;">' +
    '<button type="button" class="remove-image-btn" data-index="' + index + '" ' +
            'style="position: absolute; top: -5px; right: -5px; background: red; color: white; border: none; border-radius: 50%; width: 25px; height: 25px; cursor: pointer; font-size: 12px;">' +
      '×' +
    '</button>' +
  '</div>';
profile
백엔드 공부

0개의 댓글