简体   繁体   中英

How to write php+html in one file more beautiful?

<?
if($id == 2) {
?>
       html goes here
<?
} 
else { 
?>
       if id is not 2 then something goes here
<?
}
?>

How can I write php+html in one file more beautiful without learning smarty?

You can use PHP's alternative syntax for control structures :

<? if ($id == 2): ?>
    <h2>some html</h2>
<? else: ?>
    <h2>another html chunk</h2>
<? endif ?>

Note that short_open_tags is a php.ini directive that needs to be enabled explicitly, otherwise you would have to write <?php each time.

You can implement the MVC (Model, View, Controler) design pattern, your code can be used as a modele to load the view:

<?php
if($id == 2) 
{
 //somes variable and array controls
}
else  
{
 //somes variable and array controls
}
//include the view
include('view.php');
?>

In the view.php, you show the html page with only the echos for php variables and array.

For better possible future (design) maintainability, I'd suggest something like this:

<?php
if ($id == 2){
$someText = 'I like your id!';
}else{
$someText = 'I love your id!';
}
?>
<html>
...complex html...
<p><?php echo $someText ?></p> <!-- or <?= $someText ?> -->
...complex html...
</html>

I recommend HEREDOC for some HTML code.

Like this:

<?php
if($id==2)
 echo <<<EOT
Blah
EOT;
else
 echo <<<EOT
Your id is <b>{$id}</b>
EOT;
?>

Also, you can try an approach where you have two files: a php file and a phtml file. The php file is the main logic, then the phtml file is the html output.

Like in your example,

// logic.php file
if($id==2)
 $sOutput = 'Yes';
else
 $sOutput = 'No';
// somewhere at the end of the file
include 'logic.phtml';

// logic.phtml
<html>
<title><?=$sOutput?></title>
<body>
Blah blah blah <?=$sOutput?> you can login
</body>
</html>

As many other suggested, you could use the MVC, or if you dont like to implement a strict MVC structure, you should anyway use a templating system.

This doesnt mean that you have to learn smarty, you can write your own templating system, with just the function that you actually need.

If youre working with designers and performance is not your first point, you can build an html file with simple placeholders where the dynamic content have to go, and then replace it with php (str_replace, preg_replace).. but this will slower your application.

Example:

//html template
// the @[var] syntax is just as an example
<title>@[title]</title>
<body>
    @[content]
</body>

and your templating file:

$title = 'Hello world';
if($id == 2){
    $content = get_content();
}else{
    $content = get_another_content();
}
//really, this is just as example ;)
ob_start();
include('template.html');
$output = ob_get_clean();
echo str_replace(
    array('@[title]', '@[content]'),
    array($title, $content),
    $output
);

This is really a basic example, and has 2 problems:

  1. Performance;
  2. Designers must be instructed to NOT touch the placeholders.

A simplier solution can be:

//html template
<title><?php echo $title; ?></title>
<body>
    <?php echo $content; ?>
</body>

and php:

$title = 'Hello world';
if($id == 2){
    $content = get_content();
}else{
    $content = get_another_content();
}
include('template.php');

But echoing html should be reduced as possible, is not a good practice and it mix logic with content Logic is logic, data is data, and life is good

I like and use soulmerge 's method. But exit another more:

<?php

if ($id == 2)
echo <<< END
    <h2>some html</h2>
END;
else
echo <<< END
    <h2>another html chunk</h2>
END;

?>

You could do it like this...

<?
$html_1 = <<<EOH
my html goes here
EOH;

$html_2 = <<<EOH
my html <i>something else</i> html goes here
EOH;

echo ($id==2?$html_1:$html_2);
?>

Buuut, if you want to make it easier for your designers, just use external files:

<?
$html=($id==2 ? file_get_contents("html_1.html") : file_get_contents("html_2.html") );
$html=str_replace("%php generated content%", 1 + 1, $html );
echo $html;
?>

and use your predefined keywords to insert php calculated content (as %php generated content% getting replaced by 2 (1 + 1) in this example)

I personally don't like using short tags as I find them inconsistent amongst files and prefer sticking to one method. You can instantly make it look a bit more readable with some simple changes like so:

<? if($id == 2) {    ?>

       <p>html goes here</p>

<? } else       {    ?>

       <span>if id is not 2 then something goes here</span>

<? }                 ?>

A bit simpler than some of the other answers but also the way I'd find most readable. It's really about your own preference although a lot of other good methods have been suggested (this is just how I'd do it).

Adding to DaNieL's answer, you could do something like:

function htmlVars($html, $vars){
    $html = preg_replace_callback('/@\[([0-9a-zA-Z_\$]*)\]/',function ($matches) use ($vars){
  return isset($vars[$matches[1]])?$vars[$matches[1]]:"";
 },$html);
 return $html;
}

Example:

echo htmlVars('foo is @[foo] and bar is not @[bar]',
    Array('foo'=>'foo','bar'=>'barz'));

Result:

foo is foo and bar is not barz

Anonymous functions only work for php 5.3 or higher

There's two cases really:

1) Template code. I'd recommend soulmerge's approach of the alternate syntax for control structures.

2) Short, view-helper PHP code that generates output (usually for later substitution) that doesn't necessarily merit it's own sub-template.

For 2 I prefer something like:

public function draw(){
    $html = array();
    foreach($this->item as $item){
       $html[] = <<<EOD 
<li class="{$item->class()}">{$item->label()}</li>
EOD;
    }
    return implode($html);
}

I prefer this over any sort of wonky alternative that might involve ob_start() and ?> <?php blocks. You always want your functions to return strings, not echo output directly so that callees have the option of concatenating and otherwise manipulating results without passing the burden of output buffering on the callee.

The heredoc makes it easy to identify string output and even though I think the the breaking of the indentation is sort of ugly, it ends up being quite effective as your html output stands out like little sticky notes. That, and the fact that in my IDE (PDT), it gets nicely highlighted in green. (Not seen here in the SO highlighter...) so it's always explicit exactly what kind of "mode" I'm in.

In contrast, the ?> <?php technique makes it difficult to distinguish html from php code. Once you do it a couple of times it gets annoying to track whether you need a ?> or a <?php . Finally, it's often more verbose to do substitutions with <?php echo $obj->func() ?> vs {$obj->func()}

If your code gets more complex, then it might be time to refactor. I like heredoc because if I'm doing something ad-hoc, it'll stand out and become really obvious a couple of months down the line (ad-hoc tends to degenerate to ball of mud as you add requirements ) when I've got 40 lines of heredoc that might have started as 5. When I come back and look at my code and develope the non-totally-ad-hoc version, it's a lot easier to identify the parts of the file where I was being bad. This goes back to the sticky notes, green highlighting comment I made about the indentation as well.

By using this - PHP echo. If that's what you want, that is - it may be more readable to continue what you're doing if you're outputting large amounts of HTML.

 <?php

if($id == 2) {
  //echo all your html stuff
  echo "<title>Title is where id is 2</title>";
  echo "<h1>Hellow</h1>";

}
else {

  echo "<title>Title is where id isn't 2</title>";

}

?> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM