开发者

How to handle HTML code that repeats a lot

开发者 https://www.devze.com 2023-01-04 04:36 出处:网络
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 pra

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


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.

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>


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

function yourOtherFunction() {
$response['table'] = drawTable($item);    
return json_encode($response);
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消