简体   繁体   English

在回显中包含if语句

[英]Including an if statement inside an echo

I am echoing some HTML and would like to include an if statement in there but I cannot figure out how to approach it: 我回显了一些HTML,并希望在其中包含if语句,但无法弄清楚如何处理它:

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

I want to use the if statement to add a style to the link. 我想使用if语句向链接添加样式。

I appreciate any help. 感谢您的帮助。 Thank you. 谢谢。

Use a Ternary operation (true ? "dothis" : "doother") inside of the echo: 在回显内使用三元运算(true?“ dothis”:“ doother”):

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

Ternary operation formula is basically: 三元运算公式基本上是:

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

which is the equiv of 这是等价的

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

In an effort to prevent having a giant echo statement with inline logic, I'd include a small block of code to figure out what the style attribute value is going to be before you echo the HTML. 为了避免使用内联逻辑生成巨大的echo语句,我将包含一小段代码,以在echo显HTML之前弄清style属性值。

// 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>';

You might even venture to add a getStyle() method that does that style building to whatever your $category object. 您甚至可以冒险将getStyle()方法添加到您的$category对象中来进行样式构建。 Then you've got yourself some clean code: 然后,您将获得一些简洁的代码:

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

Here is a clean way of doing this. 这是一种干净的方法。 And make use of double quotes in echo statement if you want to pass $variables with readable HTML code. 如果要通过可读的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>";

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

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