dsa88886666 2015-04-20 17:20
浏览 39
已采纳

使用串联在HTML标记内部使用条件回显PHP函数

This is my first question.

I'm building a simple dynamic menu using <li> I'm working on a PHP based CMS (Kirby) Kirby has predefined PHP functions (helpers)

I'm trying to output a <li> for each page on the website:

<li class='active'><a href='page1'></a></li>
<li><a href='page2'></a></li>
<li><a href='page3'></a></li>
...

Im using a PHP function e($condition, $value) to style the menu item only if that page isOpen()

// I need help here
<?php 
    foreach ($pages->visible() as $p): 
    echo "<li" . e($p->isOpen(), ' class="active"') . "><a href='" . $p->url() . "'></a></li>";
    endforeach; 
?> 

The function is working but the css part class="active" is printing OUTSIDE the <li> on the final code

class="active"
<li>...</li>
<li>...</li>
<li>...</li>

I had this previous code that worked fine, but since i'm using display: inline-block the menu had spaces betwes each block, since the following code was placing each <li>in a new line.

// This code works
<?php foreach($pages->visible() as $p): ?>
<li <?php e($p->isOpen(), ' class="active"') ?> ><a href="<?php echo $p->url() ?>"></a></li>
<?php endforeach ?>

The reason i'm rewrinting the code is to remove the white space between the inline: blockelements.

I'm failing to concatenate the string in a way that the function works and print its results inside the <li>tag.

I've searched here and also have read lots of Docs in php.net but nothing worked to me, I'm struggling with this for 2 days.

I'm expecting to learn better how and when to use concatenation and string operators.

  • 写回答

1条回答 默认 最新

  • doutaoer3148 2015-04-20 17:29
    关注

    The problem is that Kirby's e() function already has the echo in the routine, instead of just simply returning the value.

    http://getkirby.com/docs/cheatsheet/helpers/e

    If you were to change your output loop to something more like this, echoing separately, you'll get the results in the desired order:

    foreach($pages->visible() as $p) 
    {
        echo "<li";
        e($p->isOpen(), ' class="active"');
        echo "> and the rest of your line </li>";
    }
    

    That said, perhaps using e() isn't the most elegant in this case. Maybe try the r() function instead:

    http://getkirby.com/docs/cheatsheet/helpers/r

    foreach($pages->visible() as $p)
    {
        echo "<li ".r($p->isOpen(), ' class="active"').">more text</li>";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么