Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I recently wrote my first WP plugin that adds a shortcode for embedding a custom jquery image gallery into posts. It's primarily just dumps a good chunk of HTML into the post, along with javascript necessary for initialization.

However, I had to build the HTML output procedurally, as a string in PHP. This kind of tag soup always drives me nuts, and I'm used to working with MVC frameworks which provide things like helper functions and partial templates for generating HTML.

What is the general approach for plugin authors who need to manage large amounts of dynamically built HTML or JS?

share|improve this question
add comment

4 Answers 4

up vote 8 down vote accepted

@Byran M. I tend to use two constructs I don't often see other WordPress developers using often, which surprises me, but I like them a lot.

1.) Heredocs

You can store large blocks of text as heredocs string that might look like this so I can store worrying about mixing single and double quotes:

   $html=<<<HTML
<input type="{$type}" size="{$size}" id="{$id}" class="{$class}" value="{$value}" />
HTML;

Note that the variables might be passed to a function as an array and then extract()ed or you could assign them in other ways. Also note that I use the braces not because they are always required but they make the code easier to read. (Of course with functions like the_content() being materially different from get_the_content() WordPress doesn't always make this style of coding easy.)

What's more, although it may not be relevant to you is if I use heredoc names like HTML, SQL, etc. then my IDE PhpStorm does syntax injection and will give me autocomplete and syntax coloring within the heredoc.

2.) String Concatenation using an Array

The other idiom I like to use is to collect the content into an array and then implode() the array. Although I've never benchmarked this so it could be less helpful than I assume I do know that repeated string concatenation is a killer as strings get larger (if anyone knows why this approach isn't any better or if you know a better approach I'd love to hear feedback):

function my_get_form_and_fields($input_items) {
    $html = array();
    $html[] = '<form name="my_form" method="get">';
    foreach($input_items as $input_item) {
        extract($input_item);
        $html=<<<HTML
<input type="{$type}" size="{$size}" id="{$id}" class="{$class}" value="{$value}" />
HTML;
    $html[] = '</form>';
    return implode("\n",$html);         
}   
share|improve this answer
1  
+1 for Heredocs, they're awesome, especially in this situation. –  Thomas McDonald Aug 12 '10 at 23:05
    
Haven't really had the time to evaluate this, but it seems like the most straightforward approach given what I need. –  Bryan M. Aug 31 '10 at 14:23
    
+1 for the array/string concatenation. I do that a lot. It makes it easy to construct strings without extraneous newlines and spaces. –  s_ha_dum Dec 15 '12 at 16:10
add comment

Checkout this function for PHP:

http://php.net/manual/en/function.ob-start.php

You can buffer an included file which would just contain html code in it, into a php variable. This will make it cleaner to maintain.

So you end up with something like this:

ob_start();
   include('path/to/my/html/file.php');
   $includedhtml = ob_get_contents();
ob_end_clean();

Then you can just return $includedhtml where you need it and it keeps your html content seperate from having to echo it all out inside of php strings.

share|improve this answer
add comment

I haven't actually used this framework, but the template model it offers will probably appeal. You might want to take a look at how the author set that up.

https://github.com/Emerson/Sanity-Wordpress-Plugin-Framework

Templates ========= Whenever possible, we should separate PHP from HTML. Within Wordpress, you'll see the two mixed together without apprehension. While this is often an "easy way" of doing things, it is almost never the "right way." Instead, we should segregate the two, thus keeping our logic pure and our views dumb. For this purpose we have the $this->render('my-template') method. A few examples:

    // From within a method in our controller
    $this->data['message'] = 'Pass this on to the template please';
    $this->render('my-template');

    // Meanwhile, in the /plugin/views/my-template.php file
    <h2>The Separation of Logic and Views</h2>
    <p><?php echo $this->data['message'];?></p>
share|improve this answer
    
It's just using output buffering, like Todd Perkins describes in his answer. –  Ian Dunn Mar 22 '12 at 0:30
add comment

That depends on the type of HTML and JS.

JavaScript

First of all, separate the dynamic parts from the static parts as much as possible. Then load whatever dynamic variables you need at runtime and queue your static scripts in the header (or footer, whatever). But this way, the majority of your JS is separate from your PHP.

HTML

This is a matter of building your code cleanly in the PHP. If you have huge chunks of HTML that you're going to re-use, I'd store those as separate variables. Then piecing things together when the shortcode is called is as simple as:

echo $firstblock;
echo $shortcodecontent;
echo $lastblock;

Rather than trying to build it out procedurally, build an object (yes, PHP supports objects) that contains all of your different HTML blocks, then instruct it which ones to use and which data to pass back. This will save you huge amounts of time.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.