如何在一个文件中编写php + html更漂亮?

goo*_*ing 7 html php

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

如何在没有学习聪明的情况下将php + html写在一个更漂亮的文件中?

sou*_*rge 23

您可以使用PHP的替代语法来控制结构:

<? if ($id == 2): ?>
    <h2>some html</h2>
<? else: ?>
    <h2>another html chunk</h2>
<? endif ?>
Run Code Online (Sandbox Code Playgroud)

请注意,short_open_tags是一个需要显式启用的php.ini指令,否则您<?php每次都必须编写.


Ami*_*uda 5

您可以实现MVC(Model,View,Controler)设计模式,您的代码可以用作加载视图的模型:

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

在view.php中,显示的html页面只包含php变量和数组的回声.

  • 使用MVC模型并不意味着View中不能有简单的逻辑.如果从Controller向View发送一个数组,你仍然需要例如foreach()来显示数组的变量.那时你回到原来的问题. (2认同)