Warm tip: This article is reproduced from serverfault.com, please click

Shopify

发布于 2020-12-02 13:48:53

What way would be best to have Blocks in Shopify but with the same style syntax? If I choose the same block twice in Shopify Theme Editor, the style of the second block gets applied. How would I get both blocks to have their own style?

What I have is like this:

Style:

<style>
{%- for block in section.blocks -%}
.announce {
   font-size: {{ block.settings.announce_text_size | append: 'px'}};
   font-weight: {{ block.settings.announce_text_weight }};    
   {%- if block.settings.announce_text_align == 'left' -%}
    padding-left: 45px;
   {%- endif -%} 
   {%- if block.settings.announce_text_align == 'right' -%}
    padding-right: 45px;
   {%- endif -%}
   color: {{ block.settings.announce_text_color }};
      }
  {%- endfor -%}
   </style>

Content:

{%- for block in section.blocks -%}
      {%- if block.type == 'announcement' -%}
    
    <div class="announce">
      
      {%- if block.settings.announce_text != blank -%}
 {{ block.settings.announce_text }}
    
      {%- endif -%}
    </div>
    {%- endif -%}
    {%- endfor -%}
Questioner
DogFoxX
Viewed
0
Bilal Akbar 2020-12-02 23:00:33

Only last style is applied because you are overriding the styles on the class. Either add the styles inline or create a unique class for each block using id. I am creating a different class for each block using block id in the code below.

<div class="page-width" data-section-id="{{ section.id }}">

  <style>
    {% for block in section.blocks %}
    .announcement-{{block.id}} {
      font-size: {{block.settings.fontSize | append: "px"}};
    }
    {% endfor %}
  </style>

  {% if section.blocks.size > 0 %}
        {% for block in section.blocks %}

        <div class="announcement-{{block.id}}">
            {{block.settings.announcementText}}
        </div>
        
        {% endfor %}
  {% endif %}

</div>



{% schema %}
{
  "name": "Test Section",
  "class": "test-section",
  "max_blocks": 5,
  "blocks": [
    {
      "type": "sample-block",
      "name": "Block",
      "settings": [
        {
          "type": "text",
          "id": "announcementText",
          "label": "Announcement Text"

        },
        {
            "type":   "range",
            "id":     "fontSize",
            "min":       10,
            "max":       50,
            "step":      4,
            "unit":      "px",
            "label":     "Font Size",
            "default":   10
        }
      ]
    }
  ]
}
{% endschema %}