tags:

views:

106

answers:

3

I have some HTML code portions that repeat a lot through pages. I put this html code inside a function so that it is easy to maintain. It works perfectly. I, however feel this may not be very good practice.

function drawTable($item){
?>
   HTML CODE HERE
<?php
}

I also run into the problem that when I want to return data using json the following won't work as it will be NULL:

$response['table'] = drawTable($item);    
return json_encode($response);

What's the correct way to handle HTML code that repeats a lot??

Thanks

+1  A: 
function drawTable( $item ) { return '<p>something</p>'; }

function yourOtherFunction() {
$response['table'] = drawTable($item);    
return json_encode($response);
}
meder
+1  A: 

Use this function definition

function drawTable($item){
  return 'HTML CODE HERE';
}

Called with

print drawTable($item);

Which will also work for your json return value.

Phil
Hey, thanks. But, I don't want to put the html code inside quotations because it is quite long chunks of html and it makes it hard to spot errors, it may involve dealing with escaping some characters and ending up with a mess... I'm trying to make the code as clean as possible
sala_7
+3  A: 

You may want to look into using templates instead of using ugly heredoc's or HTML-embedded-within-PHP-functions, which are just plain unmaintainable and are not IDE-friendly.

http://stackoverflow.com/questions/2961392/what-is-the-best-way-to-include-a-php-file-as-a-template/

If you have a repeating segment, simply load the template multiple times using a loop.

Although templates help with D.R.Y., the primary focus is to separate presentation from logic. Embedding HTML in PHP functions doesn't do that. Not to mention you don't have to escape any sort of quotes or break the indentation/formatting.

Example syntax when using templates:

$data = array('title' => 'My Page', 'text' => 'My Paragraph');

$Template = new Template();
$Template->render('/path/to/file.php', $data);

Your template page could be something like this:

<h1><?php echo $title; ?></h1>

<p><?php echo $text; ?></p>
Lotus Notes
sounds a lot like a framework. Consider a framework, it does all the plumbing code for you
ggfan
Thanks a million! I think this will do the job for now. I didn't know about the extract() function. And yes, once I'm done with this project I will consider learning CakePHP or maybe Zend Framework.
sala_7
The problem I'm finding with this approcah is that I am still not being able to return that html code as json. I thought about using something like DomDocumentFragment to load the html into a variable, but then I don't know how to use the extract() like that...
sala_7
I've been reading for the past hour and it seems the way to fix this is to use output buffering
sala_7