【问题标题】:Including an if statement inside an echo在 echo 中包含 if 语句
【发布时间】:2014-05-10 17:14:33
【问题描述】:

我正在呼应一些 HTML,并希望在其中包含一个 if 语句,但我不知道如何处理它:

echo '<li><a href="'.$category->getURL().'" style="text-decoration: none; if ($magentoCurrentUrl = $category->getURL()){ echo color:#fff; }" >'.$category->getName().'</a> </li>';

我想使用 if 语句为链接添加样式。

感谢您的帮助。谢谢。

【问题讨论】:

  • 在你的回显语句之前做你的if逻辑
  • 为什么?这就是我们有三元运算符的原因。

标签: php if-statement echo


【解决方案1】:

在 echo 内部使用三元运算(true ? "dothis" : "doother"):

echo '<li><a href="'.$category->getURL().'" style="text-decoration: none;'.($magentoCurrentUrl == $category->getURL() ? 'color:#fff;' : '').'" >'.$category->getName().'</a> </li>';

三元运算公式基本是:

echo "something: ".(true ? "dothis" : "doother")

相当于

if (true) { echo "dothis": } else { echo "doother"; }

【讨论】:

  • 任何时候,很高兴我能帮上忙!
【解决方案2】:

为了防止出现带有内联逻辑的巨大echo 语句,我将包含一小段代码来确定style 属性值在您echo HTML 之前将是什么。

// build style attribute value
$style = 'text-decoration: none';
if ($magentoCurrentUrl = $category->getURL()) { 
    $style = $style . '; color: #fff;'
}

// output HTML
echo '<li><a href="'.$category->getURL().'" style="$style" >'.$category->getName().'</a> </li>';

您甚至可以冒险添加一个 getStyle() 方法,该方法可以为您的 $category 对象构建该样式。然后你就得到了一些干净的代码:

echo '<li><a href="'.$category->getURL().'" style="'.$category->getStyle().'">'.$category->getName().'</a> </li>';

【讨论】:

    【解决方案3】:

    这是一种干净的方法。如果你想用可读的 HTML 代码传递 $variables,请在 echo 语句中使用双引号。

    if ($magentoCurrentUrl = $category->getURL())
    { 
    $color="color:#fff";
     }
     else {
     $color=" ";
     }
    echo "<li><a href='$category->getURL()' style='text-decoration: none;$color' >$category->getName()</a> </li>";
    

    【讨论】:

      猜你喜欢
      • 2013-10-18
      • 1970-01-01
      • 1970-01-01
      • 2013-06-20
      • 1970-01-01
      • 1970-01-01
      • 2018-01-02
      • 2016-01-02
      • 1970-01-01
      相关资源
      最近更新 更多