Sorry, to make it simple I’ve cut out some code. I’m trying to do a dynamic flexbox structure for the front page. Every box is a relation selected via a custom field in the front page backend.
This is the front-page.php
controller:
public function boxes()
{
$boxes = [];
if (have_rows('boxes')) {
while (have_rows('boxes')) {
the_row();
$box = get_sub_field('relation')[0];
$box->box_size = get_sub_field('size'); // size is 'full' or 'half'
$boxes[] = $box;
}
}
return $boxes;
}
This is the front-page.blade.php
:
@extends('layouts.app')
@section('content')
@while(have_posts()) @php the_post() @endphp
@include('partials.page-header')
<div class="d-lg-flex flex-row flex-wrap mt-3 w-100">
@php $first_half = true @endphp
@foreach ($boxes as $box)
@include('partials.content-front-page')
@endforeach
</div>
@endwhile
@endsection
This is the content-front-page.blade.php
:
@if ($box->post_box_size === 'full')
<div class="bg-dark d-flex justify-content-center align-items-center p-3 box mb-3 w-100 box-full">
<div class="text-white text-center box-text col-md-5">
<h2 class="h1">{{ $box->post_title }}</h2>
<p class="lead">{{ $box->post_excerpt }}</p>
</div>
</div>
@elseif ($box->post_box_size === 'half')
@if ($first_half)
@php $first_half = false @endphp
<div class="bg-dark d-flex justify-content-center align-items-center p-3 box mb-3 mr-lg-3 box-half">
<div class="text-white text-center box-text col-md-8">
<h2 class="h1">{{ $box->post_title }}</h2>
<p class="lead">{{ $box->post_excerpt }}</p>
</div>
</div>
@else
@php $first_half = true @endphp
<div class="bg-dark d-flex justify-content-center align-items-center p-3 box mb-3 box-half">
<div class="text-white text-center box-text col-md-8">
<h2 class="h1">{{ $box->post_title }}</h2>
<p class="lead">{{ $box->post_excerpt }}</p>
</div>
</div>
@endif
@endif
This code conditionally checks if the size of the box has to be full or half and if it’s half, based on the boolean variable, prints different classes for the first half and for the second half.
The problem is not related to the WordPress loop, because in the front page runs only once.
Now I’ve managed to do this in a different way and I’ve improved the code to avoid repeating the same HTML structure 3 times. But I would like to understand how I could solve this problem, to understand how to do it in the future.
I’ve understood what @alwaysblank said, but I’ve not figured out well how to solve this with his advice. If I pass a variable to the partial like suggested, can I change its value inside the partial and see it updated in the main template?
I know that’s not a well-written code, but I’m working on this. I still have to learn how to properly use Blade.