설정에서 지정된 이름으로 이미지를 참조하는 방법?

화면을 이미지(모자)로 표시하는 테마 컴포넌트에서

scss에서 이미지를 사용하려면, about.json에 정의된 다음과 같은 이미지들을 자산 이름 그대로 사용하여 작동합니다.

{
  "name": "christmas-decorations",
  "about_url": "",
  "license_url": "",
  "author": "",
  "assets": {
    "red-hat1": "assets/decorations/red-hat1.png",
    "red-hat2": "assets/decorations/red-hat2.png",
    "squirrel2": "assets/decorations/squirrel2.png",
  }
}

scss에서 이 이미지들을 사용하려면, 다음과 같이 자산 이름을 직접 사용하면 잘 작동합니다.

background: transparent url($red-hat1) top left no-repeat;

화면에 표시할 모자 이미지를 선택할 수 있는 설정을 추가하고 싶습니다.
settings.yml에는 다음과 같은 설정이 있어 화면에 표시할 모자 이미지를 선택합니다.

hat_type:
  default: red-hat1
  type: enum
  choices:
    - red-hat1
    - red-hat2
    - squirrel2

scss에서 if-else를 사용하여 이미지를 적용할 수는 있지만, 이 if-else 블록이 너무 길어질 수 있습니다 …

    @if $hat_type == "red-hat1" {
      background: url($red-hat1) no-repeat center;  
    } @else if $hat_type == "red-hat2" {
      background: url($red-hat2) no-repeat center;  
    } @else if $hat_type == "squirrel2" {
      background: url($squirrel2) no-repeat center;  
    } 

scss에서 함수를 사용해 보았습니다.

 background: url(get_image($hat_type)) no-repeat center;  

@function get_image($name){
  @return "assets/decorations/" + $name + ".png"
}

하지만 이 경우 URL이 다음과 같이 생성됩니다.
https://www.domain.com/stylesheets/assets/decorations/squirrel2.png
이것은 작동하지 않으며, 대신 다음과 같이 해석되어야 합니다 …
https://www.domain.com/uploads/db9860/original/3X/9/1/91d36fdb030047c6390f9ca85604fdbfd2e3fc12.png

누군가 힌트를 주실 수 있을까요? 정말 감사합니다 :slight_smile:

보간법(interpolation)을 사용하여 설정을 직접 사용할 수 있다고 생각합니다.

background: transparent URL("$#{$hat_type}") top left no-repeat;

Arkshine님 감사합니다.

이 문법을 사용하여 설정에서 hat_type으로 sequirrel2를 선택했습니다.

background: transparent url("$#{$hat_type}") top left no-repeat;

웹 페이지에서 스타일을 확인해 보니 이것이 다음과 같이 변환되었습니다…

추측컨대
url() 함수 내부에는 변수 $squirrel2가 필요할 텐데,
"$#{$hat_type}"은 문자열 $squirrel2를 생성하는 것 같습니다… ?


그리고 이것을 시도해 보았습니다.

background: transparent url("assets/decorations/#{$decoration_image}.png") top left no-repeat;

다음과 같이 렌더링되는데, 여전히 올바르지 않습니다.
image

해당 자산 경로 앞에 /를 추가해 보세요.

고맙습니다 @Firepup650
assets 앞에 /를 추가해 보았지만, 이 또한 작동하지 않습니다. 중간에 /가 추가되긴 하지만, 실제 URL로 변환되지 않습니다. 다음과 같은 형태여야 합니다:
https://www.domain.com/uploads/db9860/original/3X/9/1/91d36fdb030047c6390f9ca85604fdbfd2e3fc12.png

맞아요. 제 환경에서는 작동하는 줄 알았는데, 그렇지 않나 보네요. :thinking:

대안으로, js를 통해 사용자 지정 CSS 속성을 설정하는 방법을 소개합니다.

document.documentElement.style.setProperty(
  "--hat-url",
  `url(${settings.theme_uploads[settings.hat_type]}`
);
body {
  background: var(--hat-url);
}

settings.theme_uploads에는 업로드한 파일 목록이 포함됩니다.
예를 들어:
image

그런 다음 설정에 따라 사용자 지정 속성을 설정합니다.

테스트 결과, url(var(--hat-url)) 형태로 작성하면 작동하지 않아서, url()을 사용자 지정 속성에 직접 전달했습니다.