What’s a cleaner way to output HTML from a WordPress plugin?

My WordPress plugin creates a few shortcodes that return blocks of HTML.

When I register the shortcodes, I do so like this:

Read More
    add_shortcode('bb-loans-form', function() {
        return Shortcodes::loanApplicationForm();
    });

And here is the static method from the Shortcodes class:

public static function loadApplicationForm()
{
    $form = new AdamWathanFormFormBuilder;

    $html = $form->open()->action('/apply')->class('bb-loan-form');

    $html .= '<div class="bb-form-field">';
    $html .= '<h2>Loan Application Number</h2>';
    $html .= $form->text('loan_app_number')->id('loan-app-number');
    $html .= $form->submit('Continue Loan');
    $html .= '</div>';
    $html .= $form->close();

    return $html;
}

This is very cumbersome, and messy. I don’t like outputting the HTML like this. I’ve also used Heredoc, but I had to use string substitution to include important values when the form is rendered.

Is there a better way to store my HTML files? I don’t want these files publicly accessible. They would have to live in my plugin directory.

It’s not a huge plugin, so I’m not overly concerned, but I’d like to know for future reference if there’s a cleaner way to include the needed HTML.

Related posts

1 comment

  1. You could just use a single string with concatenations…

    $form = new AdamWathanFormFormBuilder;
    $html = $form->open()->action('/apply')->class('bb-loan-form') .
               '<div class="bb-form-field">
                    <h2>Loan Application Number</h2>' .
                    $form->text('loan_app_number')->id('loan-app-number') . 
                    $form->submit('Continue Loan') .
               '</div>' .
            $form->close();
    
    return $html;
    

    It at least keeps the HTML aligned.

    I also don’t really see an issue with Heredoc, as long as you assign variables and substitute them in:

    $form = new AdamWathanFormFormBuilder;
    
    $form_start = $form->open()->action('/apply')->class('bb-loan-form');
    $loan_app = $form->text('loan_app_number')->id('loan-app-number');
    $submit = $form->submit('Continue Loan');
    $form_end = $form->close();
    
    $html = <<<HTML
        {$form_start}
            <div class="bb-form-field">
                <h2>Loan Application Number</h2>
                {$loan_app}
                {$submit}
            </div>
        {$form_end}
    HTML; 
    
    return $html;
    

Comments are closed.