Separation of logic and markup for variable fields

Jumping into Sage from a more traditonal WP dev approach and trying to get my head around the separation of logic and markup in the templates.

I have a bunch of ACF fields that are optional. Here’s a simplified example of the setup:

Controller:

namespace App\Controllers;

use Sober\Controller\Controller;

class SingleProducer extends Controller
{

  public function producerShortDescription()
  {
    return get_field('producer_short_description');
  }  

}

View:

<article @php post_class() @endphp>
  <header>
    <h1 class="entry-title">{!! get_the_title() !!}</h1>
  </header>
  <div class="entry-content">
    <p>{!! $producer_short_description !!}</p>
  </div>
</article>

Let’s say the WP author doesn’t want to add content for the “producer_short_description” field so this is blank. I am then left with the output of an empty <p></p> in the front end:

<div class="entry-content">
    <p></p>
</div>

A solution would be to have conditional logic to only output the entire <p>!! $producer_short_description !!}</p> block if the author chooses to include it, but that would mean putting markup into the logic. Or, i could do this:

<article @php post_class() @endphp>
  <header>
    <h1 class="entry-title">{!! get_the_title() !!}</h1>
  </header>
  <div class="entry-content">
    @if ($producer_short_description)
      <p>{!! $producer_short_description !!}</p>
    @endif
  </div>
</article>

But this includes logic in the view.

What’s the best practice here?

Thanks

I would say that your last example is pretty valid. I don’t think that having some very simple if statements spread across the template is something bad.

Especially that in the real world scenarios you won’t be able to avoid that unless you make your templates very very granular (for example the description could be a “sub-template” - but then you exchange a little bit of logic with endless includes or other render methods).

Thank you for your opinion on this. Learning as I go. Comparing my usual way of doing this (all the ACF stuff in the template pretty much as per the ACF docs) versus this appraoch (especially with the Controller ACF moduile) really does dry things out massviely, and yes conditionals or loops in the view seems perectly accpetable from the examples I’m seeing.

This topic was automatically closed after 42 days. New replies are no longer allowed.