0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【初心者向け】Shopify App Block開発でcssをidユニークに構築する

Posted at

問題提起

liquidでは、ブロックごとにcssをユニークにしないと、スキーマを変更したときに、同じ種類のブロックすべての見た目が変わってしまうため良くない。

だからCSSクラス名に{{ block.id }}をハイフン結合して、ブロックごとにスキーマを変更できるようにする。

しかし、全てのCSSに{{ block.id }}を付けるのは能がない気がする。

この記事では、「CSSにある文字列を付けることによって、HTMLのクラス指定にはblock.idは付けなくても大丈夫だよ」という話。

☓悪い例

.liquid
{% comment %} アップブロックの UI を作成 {% endcomment %}
<!-- ここにHTMLのコードを書く -->

{% comment %} 見出しが設定されていないときは非表示にする {% endcomment %}

<div class='ranking-heading-margin-{{ block.id }'>
    <h2 class='ranking-heading-text'>
       //テキスト
    </h2>
</div>

{%- style -%}
 .ranking-heading-margin-{{ block.id }} {
    //cssプロパティ
  }
{%- endstyle -%}

{% schema %}
{
    ...
{% endschema %}

何が悪いかというと、cssクラスを適用するHTMLタグが増えると、その分毎回-{{ block.id }}を追加しなければならない。しんどい。

◯良い例

.liquid
{% comment %} アップブロックの UI を作成 {% endcomment %}
<!-- ここにHTMLのコードを書く -->

{% comment %} 見出しが設定されていないときは非表示にする {% endcomment %}

<div class='ranking-heading-margin'>
    <h2 class='ranking-heading-text'>
        {{ block.settings.text }}
    </h2>
</div>


{%- style -%}
  #shopify-block-{{ block.id }}.アプリID .ranking-heading-margin {
    //cssプロパティ
  }

{%- endstyle -%}
  
{%- endstyle -%}

{% schema %}
{
    ...
{% endschema %}

CSSの定義時に#shopify-block-{{ block.id }}.を付け加えれば、それ以下のCSSクラスを持ったHTML要素すべてが自動でidユニークになる。

便利。

結論

ありがとうShopify
今度はエラーハンドリングを実装してね。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?