在echo中包含if语句


Including an if statement inside an echo

我正在响应一些HTML,并希望在那里包含一个if语句,但我不知道如何接近它:

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

我想用if语句给链接添加一个样式。

我很感激你的帮助。谢谢你。

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

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 " dother ";}

在努力防止具有内联逻辑的巨大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>';

这里有一个简洁的方法。如果你想用可读的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>";