phpwordpressroots-sage

How to add fallbacks to partial included with Sage 10's @include?


Let's say I have created a button component I want to include into my project with Sage 10's @include function, how do I add fallbacks to the variables, in case I or another user forget to add a value?

My button*:

<button class="<?= esc_attr($button_class); ?>">
         <?= esc_html($button_label); ?>
</button>

My include

@include('partials.button', [
  'button_class' => 'btn btn-primary',
  'button_label' => 'label', 
])

How can I add fallbacks, so button isn't empty if I don't add button_label?

*Code is simplified for this example


Solution

  • In the external PHP-file, with the button, you can add the variables between some PHP-tags, to catch any empty variables and instead return a fallback.

    In this case, the PHP-file with the <button> element would look like this:

    <?php
      $button_class = $button_class ?: 'lg:block w-full lg:w-auto btn btn-primary mr-4';
      $button_label = $button_label ?: __( 'Insert text here', 'fallback', 'edc' );
    ?>
    
    <button class="<?= esc_attr($button_class); ?>">
             <?= esc_html($button_label); ?>
    </button>
    

    Sage will first apply the variables from the @include-part to the variables in the top, after which PHP uses the value as is after the closing ?>-tag.