사용자 기본 설정에 따라 Drupal 8(또는 9)에서 다크 모드와 라이트 모드 간을 전환하는 방법

게시 됨: 2020-09-15

사용자에게 자신의 선호도에 따라 인터페이스를 사용자 정의할 수 있는 자유를 준다면 얼마나 좋을까요? 많은 사용자가 밝은 인터페이스(어두운 텍스트가 있는 밝은 배경)를 선호하지만 일부 사용자는 어두운 인터페이스(밝은 텍스트가 있는 어두운 배경)를 선택합니다. 어두운 인터페이스는 멋지고 트렌디한 것으로 인식되는 반면 일부는 특히 화면 앞에서 많은 시간을 보내는 개발자의 경우 눈의 피로를 줄여준다고 생각합니다. 사용자에게 옵션을 제공하는 것은 접근성과 사용자 경험 측면에서 엄청난 승리라고 생각합니다. 이를 수행할 수 있는 몇 가지 방법이 있습니다. 이 기사에서는 다크/라이트 웹 디자인 모드를 전환하고 Drupal 8 또는 Drupal 9에서 구현하는 방법에 대해 설명합니다.

다크/라이트 토글 구현


이를 구현하는 두 가지 방법에 중점을 둘 것입니다.
1. CSS만 사용합니다.
2. CSS 및 JS 토글 스위치 구현

CSS만 사용

CSS만 있는 웹사이트에서 다크 모드를 구현하려면 몇 가지 시스템 요구 사항을 염두에 두어야 합니다. 이러한 중요한 요구 사항 중 하나는 시스템 전체의 다크 모드 입니다. 사용자가 자신의 PC에서 어두운 모드를 사용하는 것을 선호하는 경우 사용자는 밝은 텍스트와 함께 어두운 색상의 배경을 보여주는 웹사이트를 보게 됩니다. 기본 색상 구성표 (미디어 쿼리)는 사용자가 시스템에 밝은 색상 또는 어두운 색상 테마를 사용하도록 요청했는지 식별하는 데 사용됩니다.

구현:

1. CSS 변수를 선언합니다.
2. 필요할 때마다 변수를 사용합니다.

결과:

참고: 지원되지 않는 일부 장치에서 결과를 에뮬레이트하려면 F12를 눌러 DevTool을 입력하기만 하면 됩니다. 다음으로 CTRL+SHIFT+P를 누른 다음 선호하는 색상 구성표: 어둡게 검색하고 Enter 키를 누릅니다.

CSS 및 JS 토글 스위치 구현

이 접근 방식을 사용한다면 시스템 요구 사항에 대해 신경 쓸 필요가 없습니다. CSS와 JS 몇 줄만 작성하면 준비가 완료됩니다. 변수를 초기화하고 나면 스타일시트에서 이러한 변수를 참조할 수 있습니다. 이것은 다크 모드와 라이트 모드 사이를 토글하는 HTML 구조가 될 것입니다.

HTML 구조
HTML 구조


그리고 CSS의 일부 라인은 이 전환을 초래해야 합니다.

스위치
스위치

마지막 부분은 모든 것을 하나로 묶기 위해 약간의 JavaScript를 추가하는 것입니다.
● 향후 방문을 위해 사용자 기본 설정 저장
● 웹사이트 로드 시 저장된 사용자 기본 설정이 있는지 확인합니다(있는 경우).

그게 다야! 아래에서 전체 데모를 확인하세요.

또는 여기를 클릭하여 데모를 보십시오.

Drupal 8(또는 Drupal 9)에서 Dark/Light 토글 구현

맞춤형 Drupal 8 테마를 만드는 것으로 시작하려면 여기에서 멋진 기사를 참조하세요. 이제 Drupal 8 또는 Drupal 9에서 어두운 테마/밝은 테마를 사용하는 방법을 보여주는 테마 만들기를 시작하겠습니다.

파일 구조는 다음과 같습니다.

다크/라이트 토글 구현

이제 page.html.twig 내부의 헤더 섹션을 다음 코드로 업데이트합니다.

 <header aria-label="Site header" role="banner"> <div class="container"> <div class="header"> {{ page.branding }} {{ page.navigation }} <div class="switch-wrapper"> <label class="switch" for="checkbox"> <input type="checkbox"/> <div class="slider round"></div> </label> </div> </div> </div> </header>

나머지 HTML 구조는 디자인이나 요구 사항에 따라 달라집니다.
HTML 구조가 끝나면 CSS에서 요소의 스타일을 지정하여 보기 좋게 만들 차례입니다.
먼저 Light/Dark 모드의 색상을 담당할 모든 기본 변수를 생성해야 합니다.

 style.css :root { --color-background: #f0f0f0; --color-header: rgb(14, 33, 141); --color-header-text: #aecafa; --color-text: #2c0000; --color-card-bg: #fff; --color-link: rgb(255, 0, 0); } /* Variable decleration for dark mode */ [data-theme="dark"] { --color-background: #1a1a1a; --color-header: #aecafa; --color-header-text: 0e218d; --color-text: #d3d3d3; --color-card-bg: #435561; --color-link: #24ce24; }

이제 변수 정의가 완료되었으므로 헤더 섹션에 스타일을 추가하여 필요한 결과를 얻을 차례입니다.

 style.css .header { display: flex; justify-content: space-between; align-items: center; padding: 10px; border-bottom-right-radius: 10px; border-bottom-left-radius: 10px; background-color: var(--color-header); } .header a { color: var(--color-header-text); text-decoration: none; font-weight: bold; } .region-navigation { display: flex; justify-content: center; } ul.menu { display: flex; justify-content: center; } ul.menu li { margin-right: 30px; } .switch-wrapper { display: flex; align-items: center; } .switch { display: inline-block; height: 34px; position: relative; width: 60px; } .switch input { display: none; } .slider { background-color: white; bottom: 0; cursor: pointer; left: 0; position: absolute; right: 0; top: 0; transition: 0.4s; } .slider:before { background-color: rgb(255, 196, 0); bottom: 4px; content: url("../assets/sunny-day.svg"); height: 26px; left: 4px; position: absolute; transition: 0.4s; width: 26px; } input:checked + .slider { background-color: rgb(36, 36, 36); } input:checked + .slider:before { transform: translateX(26px); content: url("../assets/night.svg"); background-color: rgb(59, 116, 223); } .slider.round { border-radius: 34px; } .slider.round:before { border-radius: 50%; }
style.css .header { display: flex; justify-content: space-between; align-items: center; padding: 10px; border-bottom-right-radius: 10px; border-bottom-left-radius: 10px; background-color: var(--color-header); } .header a { color: var(--color-header-text); text-decoration: none; font-weight: bold; } .region-navigation { display: flex; justify-content: center; } ul.menu { display: flex; justify-content: center; } ul.menu li { margin-right: 30px; } .switch-wrapper { display: flex; align-items: center; } .switch { display: inline-block; height: 34px; position: relative; width: 60px; } .switch input { display: none; } .slider { background-color: white; bottom: 0; cursor: pointer; left: 0; position: absolute; right: 0; top: 0; transition: 0.4s; } .slider:before { background-color: rgb(255, 196, 0); bottom: 4px; content: url("../assets/sunny-day.svg"); height: 26px; left: 4px; position: absolute; transition: 0.4s; width: 26px; } input:checked + .slider { background-color: rgb(36, 36, 36); } input:checked + .slider:before { transform: translateX(26px); content: url("../assets/night.svg"); background-color: rgb(59, 116, 223); } .slider.round { border-radius: 34px; } .slider.round:before { border-radius: 50%; }

스타일은 요구 사항에 따라 다를 수 있습니다. 모든 스타일링이 끝나면 이제 Jquery 코드에서 일부 기능을 작성할 차례입니다. Jquery 코드는 다음과 같습니다(이 경우 script.js).

 script.js (($, Drupal) => { Drupal.behaviors.mainMenu = { attach(context) { const toggleSwitch = document.querySelector( '.switch input[type="checkbox"]' ); const currentTheme = localStorage.getItem("theme"); if (currentTheme) { document.documentElement.setAttribute("data-theme", currentTheme); if (currentTheme === "dark") { toggleSwitch.checked = true; } } function switchTheme(e) { if (e.target.checked) { document.documentElement.setAttribute("data-theme", "dark"); localStorage.setItem("theme", "dark"); } else { document.documentElement.setAttribute("data-theme", "light"); localStorage.setItem("theme", "light"); } } toggleSwitch.addEventListener("change", switchTheme, false); }, }; })(jQuery, Drupal);
script.js (($, Drupal) => { Drupal.behaviors.mainMenu = { attach(context) { const toggleSwitch = document.querySelector( '.switch input[type="checkbox"]' ); const currentTheme = localStorage.getItem("theme"); if (currentTheme) { document.documentElement.setAttribute("data-theme", currentTheme); if (currentTheme === "dark") { toggleSwitch.checked = true; } } function switchTheme(e) { if (e.target.checked) { document.documentElement.setAttribute("data-theme", "dark"); localStorage.setItem("theme", "dark"); } else { document.documentElement.setAttribute("data-theme", "light"); localStorage.setItem("theme", "light"); } } toggleSwitch.addEventListener("change", switchTheme, false); }, }; })(jQuery, Drupal);

그리고 theme_name.libraries.yml 파일에 JS 및 CSS 파일을 포함하는 것을 잊지 마십시오.

 global-styling: version: 1.x css: theme: css/style.css: {} js: js/script.js: {} dependencies: - core/jquery - core/drupal
global-styling: version: 1.x css: theme: css/style.css: {} js: js/script.js: {} dependencies: - core/jquery - core/drupal

이제 결과를 보려면 사이트 캐시를 지우십시오. 최종 결과는 다음과 같아야 합니다.

결과

Drupal 8에서 다크 모드와 라이트 모드 간 전환