[Liquid]GETクエリの値を取得する
https://xxxx.myshopify.com/search?type=product のtypeの値を取得したい時のLiquidでの処理を紹介いたします。
下記コードをファイル名:snippets/function_get_query_value_by_key.liquidで保存します。
{%- capture contentForQuerystring -%}{{ content_for_header }}{%- endcapture -%}
{%- assign pageUrl = contentForQuerystring | split:'"pageurl":"' | last | split:'"' | first | replace:'\/','/' | replace:'%20',' ' | replace:'\u0026','&' -%}
{%- assign get_query_value_by_key = '' -%}
{%- if pageUrl contains "?" -%}
{%- assign pageQuerystring = pageUrl | split:'?' | last | replace:'=','&' -%}
{%- assign tmp = pageQuerystring | split:'&' -%}
{%- for kv in tmp -%}
{%- if kv == key -%}
{%- assign get_query_value_by_key = tmp[forloop.index] -%}
{%- break -%}
{%- endif -%}
{%- endfor -%}
{%- endif -%}
Liquid上の取得したい所で下記コードでsnippets/function_get_query_value_by_key.liquidをインクルードします。
{%- include "function_get_query_value_by_key" key:"type" -%}
上記コード以降は変数「get_query_value_by_key」に文字列「product」が格納されています。
キーが「title」の時は下記コードのようにkeyに「title」を指定して下さい。
{%- include "function_get_query_value_by_key" key:"title" -%}
※includeの代わりにrenderが推奨されていますが、renderでは親テンプレートに値を渡せないためincludeを使用しています。
参考リンク
https://community.shopify.com/c/Shopify-Design/URL-Parameters-in-LIQUID/td-p/149761/page/2
Shopifyを利用したストアの構築・運用のご相談は株式会社メタフェイズまで!
この記事が気に入ったらサポートをしてみませんか?