简体   繁体   English

有条件地回显打开和关闭HTML标签

[英]Conditionally echo opening and closing HTML tags

A lot of times in PHP, it is necessary to conditionally echo opening and closing tags. 在PHP中很多时候,必须有条件地回显打开和关闭标签。 For example, when getting a list of elements, you only want to include the <ul> ... </ul> if there are more than 0 elements ( <li> s) to display. 例如,在获取元素列表时,如果要显示的元素( <li> )多于0个,则只想包含<ul> ... </ul>即可。 The most obvious solution is like this: 最明显的解决方案是这样的:

<?php
    $count = getCount();
    if($count > 0) {
        echo "<ul>";
    }
    for($i = 0; $i < $count; $i++) {
         // echo our items
         echo "<li>" . getItem() ."</li>";
    }
    if($count > 0) {
        echo "</ul>";
    }
?>

But we have the same if( ... ) twice. 但是我们有两次相同的if( ... ) Is there a better way to conditionally echo the <ul> tags ? 有没有更好的方法来有条件地回显<ul>标签?

Here you go... one if : 在这里你去...一个if

<?php
    $count = getCount();
    if($count > 0) {
        echo "<ul>";
        for($i = 0; $i < $count; $i++) {
            // echo our items
            echo "<li>" . getItem() ."</li>";
        }
        echo "</ul>";
    }
?>

This also skips an unnecessary for loop, which you currently have in your code :) 这也会跳过不必要的for循环,您当前在代码中有:)

Of course I jest a bit. 我当然开玩笑了。 Once you finally get past the point of wanting to write spaghetti code, then you can look into various templating engines. 一旦您终于摆脱了想要编写意大利面条式代码的地步,那么您就可以研究各种模板引擎。

输出HTML的更好方法是使用模板引擎,而不是直接通过PHP代码输出任何HTML。

You don't need two if statements. 您不需要两个if语句。 You can just do it all in one statement. 您可以在一个语句中完成所有操作。

if($count > 0) {
    echo "<ul>";
    for($i = 0; $i < $count; $i++) {
     // echo our items
     echo "<li>" . getItem() ."</li>";
    }
    echo "</ul>";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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