根据条件插入 HTML 标记


inserting html tags based on condition

使用php,我希望根据是否满足条件将div标签包裹在一些内容周围。目前,我正在执行此操作,如以下示例所示。有没有更好的方法?它似乎不是很专业。

<?php if($Subject) echo "<div id='someID'>";?>
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem
 Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown
 printer took a galley of type and scrambled it to make a type specimen book. It has 
survived not only five centuries, but also the leap into electronic typesetting, remaining
 essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets
 containing Lorem Ipsum passages, and more recently with desktop publishing software like
 Aldus PageMaker including versions of Lorem Ipsum.</p>
<?php if($Subject) echo "</div>";?>
你可以

通过隐藏div来做这样的事情

  <div id="someID" <?php if (!$Subject){?>style="display:none"<?php } ?>>

很难假设问题的整个上下文(最好多写一点关于$subject的值来自哪里以及它可能是什么值)。

但是假设$subject可以是一组指定的值,您可以尝试如下操作:

$text = 'Some arbitrary text';
$allowedWrappers = array(
    'one'   => 'someID',
    'two'   => 'anotherID',
    'three' => 'yetAnotherID'
);
if(isset($subject) && in_array($subject, $allowedWrappers)) {
    echo '<div id="'.$allowedWrappers[$subject].'"><p>'.$text.'</p></div>';
} else {
    echo '<p>'.$text.'</p>';
}