内联PHP/HTML三进制If [英] Inline PHP / HTML Ternary If

查看:47
本文介绍了内联PHP/HTML三进制If的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试执行以下操作:

I am trying to do the following:

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

但是它不起作用.

我要实现的目标是可能的吗?如果是这样,我在做什么错了?

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

我知道将PHP放入HTML大声笑并不难.我很好奇是否可以以类似于以下方式使用三元运算符:

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 }?>

推荐答案

您所做的只会返回值"class ='current'".仍然需要您对它进行回显/打印.

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>

我在这里所做的是将class属性放置在php之外,以使内容保持整洁,如果该值的值为true,则在这种情况下将三元返回的值当前"回显.

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>

这篇关于内联PHP/HTML三进制If的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆