設定で指定された名前で画像を参照する方法

テーマコンポーネントで、画面に画像(帽子)を表示する場合についてです。

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:

補間を使用して設定を直接使用できると思います。

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

Arkshineさん、ありがとうございます。

この構文で、設定の hat_typesquirrel2 に選択しました。

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

その assets パスの先頭に / を追加してみてください。

@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() をカスタムプロパティに直接渡しました。

「いいね!」 1