0
<?php
  $typeface = $page->typeface();
    if($typeface == '') {
  } else {
      echo '<li><span>Typeface: </span>'.$typeface.'</li>';
  }
?>


我最初尝试了下面的 PHP 代码,但它仍然会输出 HTML:
<li><span>Typeface: </span></li>即使字符串为空。


<?php $typeface =  $page->typeface(); 
  if (!empty($typeface)): ?>
    <li><span>Typeface: </span><?php echo $typeface ?></li> 
  <?php endif; ?>


所以我的问题是,我怎样才能以更短的方式在最顶部编写代码?

4

5 回答 5

3
$typeface = trim($page->typeface());
if($typeface != '')
    echo '<li><span>Typeface: </span>'.$typeface.'</li>';

编辑:(删除新行)

$typeface = trim(str_replace(array("\r", "\r\n", "\n"), '', $page->typeface()));
if($typeface != '')
    echo '<li><span>Typeface: </span>'.$typeface.'</li>';
于 2012-12-08T09:09:42.123 回答
2

试试这个

(isset($typeface) && !empty($typeface))?echo "<li><span>Typeface: </span>".$typeface."</li>":"";
于 2012-12-08T09:16:09.730 回答
0
($typeface=="")?echo "":echo '<li><span>Typeface: </span>'.$typeface.'</li>';
于 2012-12-08T09:19:00.627 回答
0

根据$page->typeface()方法的返回类型和代码的位置(看起来你在模板视图上),我可能会选择:

<?php if ($typeface === $page->typeface()): ?>
    <li><span>Typeface: </span><?=$typeface?></li>
<?php endif; ?>

PHP文档在这里:

控制结构的替代语法

请参阅此处<?=...?>了解使用短标签时应注意的事项。

一个替代方案<?=...?>是:<?php echo $typeface; ?>.

希望有帮助!


编辑:

实际上,我早些时候对自己进行了第二次猜测(我责怪睡眠不足)。我最初有这个代码(除了trim()):

<?php if ($typeface = trim($page->typeface())): ?>
    <li><span>Typeface: </span><?=$typeface?></li>
<?php endif; ?>

我在哪里设置$typeface变量if()。这种技术应该将您的代码缩短一行。

这是一个使用简单字符串的工作示例:

<?php $foo = ""; ?>
...
<?php if ($typeface = trim($foo)): ?>
    <li><span>Typeface: </span><?=$typeface?></li>
<?php endif; ?>

...输出:没有。

<?php $foo = 'I\'m a string!'; ?>
...
<?php if ($typeface = trim($foo)): ?>
    <li><span>Typeface: </span><?=$typeface?></li>
<?php endif; ?>

...输出:(<li><span>Typeface: </span>I'm a string!</li>显然,缺少开头和结尾<ul></ul>

于 2012-12-08T09:22:30.573 回答
0

试试这个..

$typeface = $page->typeface();
echo $res=($typeface != '')?'<li><span>Typeface: </span>'.$typeface.'</li>':'';
于 2012-12-08T09:37:38.307 回答