Inline PHP / HTML Ternary If

安稳与你 提交于 2021-01-21 08:22:20

问题


I am trying to do the following:

<li <?PHP ($this->pageName == 'index' ? ?>class="current"<?PHP : '')?>><a href="">Home</a></li>

But it is not working.

Is what I'm trying to achieve possible? If so what am I doing wrong?


I know it's not hard to put PHP in HTML lol. I was curious if a ternary operator could be used in a way that is similar to:

<?PHP if(1 == 1){?>
<p>Test</p>
<?PHP }?>

回答1:


What you have done will only RETURN the value "class='current'". You still will be required to ECHO/PRINT it to have it applied.

The code below should get it working fine.

<li class="<?PHP echo ($this->pageName == 'index')? 'current': ''; ?>">
    <a href="#">Home</a>
</li>

What I've just done here is place the class attribute outside of the php so as to keep things neater and ECHOed the value returned by ternary in this case "current", if the value evaluates to true.

For test purposes, you can try the line of code below toggling the values being compared.

<li class="<?PHP echo ( 1 == 0 )? 'current': ''; ?>">
    <a href="#">Home</a>
</li>



回答2:


<li <?PHP ($this->pageName == 'index') ? ?> class="current" <?PHP : '' ?>><a href="">Home</a></li>

I doubt, what you are trying to do would even work, because the logic of the ternary operator is

if condition ? Yes/true : No/false ;

What replaces Yes/true in your code segment?




回答3:


Also, you can use PHP shorthand for this, I'm not exactly sure what youre trying to do, but have an idea, look at this code and see if you can figure it out:

<li <?=($this->pageName == 'index') ? "class='current'" : ''?>><a href="">Home</a></li>

everything in the parenthesis() is the if conditional\comparative. The

来源:https://stackoverflow.com/questions/16405986/inline-php-html-ternary-if

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!