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 SPSS分类模型实训题步骤
  • ¥15 求解决扩散模型代码问题
  • ¥15 工创大赛太阳能电动车项目零基础要学什么
  • ¥20 limma多组间分析最终p值只有一个
  • ¥15 nopCommerce开发问题
  • ¥15 torch.multiprocessing.spawn.ProcessExitedException: process 1 terminated with signal SIGKILL
  • ¥15 QuartusⅡ15.0编译项目后,output_files中的.jdi、.sld、.sof不更新怎么解决
  • ¥15 pycharm输出和导师的一样,但是标红
  • ¥15 想问问富文本拿到的html怎么转成docx的
  • ¥15 我看了您的文章,遇到了个问题。