Use complicated html structure with theme blocks in main-product

Shiref
Shopify Partner
9 0 1

Hello, I have a bit complex code in main-product section. there's a lot of nested elements to adjust styles on desktop and mobile. so for example for title and price I have something like this

 

<div class="title_and_price flex justify-between md:flex-col">
    <div>
        <div>{{ title }}</div>
        <div>{{ vendor }}</div>
    </div>
    <div>{{ price }}</div>
</div>

 

this is just a basic example, the code is actually nested more than that. and it's required to be like this for style needs.

so I want to support blocks and I see in dawn theme it doesn't have any nested HTML within blocks so it goes with each case normally, but in my case how would I go for supporting blocks? here's my initial code to support blocks but it won't work because case & when can't be in nested HTML. 

 

<div class="title_and_price flex justify-between md:flex-col">
    {%- for block in section.blocks -%}
        {%- case block.type -%}
            <div>
                {%- when 'title' -%}
                    <div>{{ title }}</div>
                {%- when 'vendor' -%}
                    <div>{{ vendor }}</div>
            </div>
                {%- when 'price' -%}
                    <div>{{ price }}</div>
        {% endcase %}
    {% endfor %}
</div>

 

 

Of course this won't work and here's where I need your help, I can't flatten my html to be without nesting.. so how can I support blocks?

Reply 1 (1)

Mehedi06
Shopify Partner
5 0 1

Hi, 

The HTML nesting thing you're trying to achieve can be done but your coding approach is wrong. Let me walk-through it.


What is the current issue?

You have one starting 'div' tag which is declared before the first 'when' block ('title' block). Then you tried to close this 'div' after the second 'when' block ('vendor' block) element. The issue is that the closing 'div' element is already inside another 'when' block. This is an incorrect structure. So, the opening 'div' tag can't find the closing one and the closing 'div' can't find the opening tag. You can't put your structure inside this kind of condition. 

You can try it on the shopify code editor and can see for yourself the issue.

 

Mehedi06_0-1718454455565.png

 

What Can we do to nest some of the blocks?

We just have to use different for loop for different nesting blocks and that would solve your problem. 

 

Mehedi06_1-1718457674371.png

Mehedi06_0-1718458445560.png