Liquid Snippets by ALSEL
🧰 ユーティリティ中級

ランダムな商品を取得

ストア内のすべての商品、または指定したコレクションからランダムに1つの商品を抽出するスニペット。タイムスタンプをシード値として使い、毎回異なる商品を取得する。

用途
トップページやサイドバーに「本日のおすすめ商品」枠を出したい、または関連商品セクションで多様性を持たせたいときに活用。
設置場所
snippets/random-product.liquid に配置し、テンプレートやセクション内で `{% render 'random-product' %}` または `{% render 'random-product' with specific_collection: 'コレクションハンドル' %}` で呼び出す。その後 `{{ random_product }}` で商品オブジェクトにアクセス可能。
注意点
コレクションが空の場合や指定したハンドルが存在しないときは `random_product` が空になるため、テンプレート側で `{% if random_product %}` で存在確認する。タイムスタンプベースの乱数生成のため、同一秒内なら同じ商品が返される。より均等なランダム性が必要なときは Shopify Functions や JavaScript の `Math.random()` に切り替える検討も推奨。
タグ:productrandomcollectionutilitytimestamp

コード

32 行 / liquid
{%- comment -%}
    Basic usage to get a random product from all your shop :
    {%- render 'random-product' -%}
    {{ random_product }} -> here's your random product

    Basic usage to get a random product from a specific collection :
    {%- render 'random-product' with specific_collection: 'sport' -%}
    {{ random_product }} -> here's your random product
{%- endcomment -%}

{%- if specific_collection -%}
    {%- assign all_products_from_collection = collections[specific_collection].products -%}
{%- else -%}
    {%- assign all_products_from_collection = collections['all'].products -%}
{%- endif -%}

{%- assign all_products_random = '' -%}

{%- for product_splitted in all_products_from_collection -%}
    {%- assign all_products_random = all_products_random | append: product_splitted.handle | append: ',' -%}
{%- endfor -%}

{%- assign all_products_random_splited = all_products_random | split: ',' -%}

{%- assign min = 0 -%}
{%- assign max = all_products_random_splited.size | minus: 1 -%}
{%- assign diff = max | minus: min -%}
{%- assign random_number = "now" | date: "%N" | modulo: diff | plus: min -%}

{%- assign random_product_slug = all_products_random_splited[random_number] -%}
{%- assign random_product = all_products[random_product_slug] -%}

出典・ライセンス

License:
MIT

このコードは pgrimaud 著作の MIT ライセンスソースです。 原本の著作権は pgrimaud が保有します。日本語訳は ALSEL によるものです。

関連項目

🧰 ユーティリティ初級

コメント後の空白フォーマット

Liquid コメントタグの直後に改行や空白がある場合の正しいフォーマット例。prettier-plugin-liquid によるコード整形テストケース。

📁 theme-tools·MIT·6
🧰 ユーティリティ初級

Liquidコメントのフォーマット

Liquid のコメントタグ直後に改行がある場合の正しいフォーマット例。prettier-plugin-liquid による自動整形テストケース。

📁 theme-tools·MIT·6
🧰 ユーティリティ初級

セクション呼び出しの改行制御

{% sections %} タグの前後の空白制御(ホワイトスペース削除演算子 `{%-` と `-%}` の使い方)を示すサンプル。Prettier による Liquid コードフォーマットで改行が崩れないことを確認するテストケース。

📁 theme-tools·MIT·7
🧰 ユーティリティ初級

Prettier フォーマッタの HTML リスト整形テスト

Prettier Liquid プラグインが HTML のリスト要素(ul / ol)をどのように整形・改行するかをテストするサンプルコード。短い行は1行、長い行は複数行に自動で分割される動作を検証する。

📁 theme-tools·MIT·8
🧰 ユーティリティ上級

Vue.js属性のLiquid整形

Vue.js のディレクティブ(@click、:class など)を含む Liquid コードを Prettier で正しく整形するテストケース。spec 準拠の属性名を保持したまま、改行・インデント処理を行う。

📁 theme-tools·MIT·9
🧰 ユーティリティ上級

sections タグのフォーマット

Liquid の sections タグ構文と、Prettier によるフォーマット時の動作を示すテストファイル。タグ名の直前・直後の空白や改行が保持される仕様を確認するサンプル。

📁 theme-tools·MIT·9