Question

I am echoing some HTML and would like to include an if statement in there but I cannot figure out how to approach it:

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.

I appreciate any help. Thank you.

Was it helpful?

Solution

Use a Ternary operation (true ? "dothis" : "doother") inside of the echo:

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

OTHER TIPS

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.

// 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. 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.

if ($magentoCurrentUrl = $category->getURL())
{ 
$color="color:#fff";
 }
 else {
 $color=" ";
 }
echo "<li><a href='$category->getURL()' style='text-decoration: none;$color' >$category->getName()</a> </li>";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top