0

例如,我有一个具有非常特定格式的列表,我想一遍又一遍地放入不同的内容。

所以我可能有一个功能:

<?
function fancy_container (contents_array) {
  <?
    <ul>
      <? for($contents_array as $content) { ?>
        <li class='special'><? echo $content ?><div class='other-specials'></div></li>
      <? } ?>
    </ul>
  ?>
}
?>

这行得通,但我想这样称呼它:

<?
  fancy_container(array(?>
    <div class='whatever'>hi there</div>
    <div class='whatever'>hi there</div>
    <div class='whatever'>hi there</div>
  <?), ?>
    <div class='other-junk'>hiya</div>
    <div class='other-junk'>hiya</div>
    <div class='other-junk'>hiya</div>
  <?))
?>

我想出了如何使用heredoc来做到这一点,但这似乎有点讨厌。我会以错误的方式解决这个问题吗?我不是 php 人,所以我不熟悉正常的做事方式或限制。我知道如何使用 ruby​​ yield 来做到这一点,但在 php 中不知道。

我只想将 html 内容注入一个容器(或多个容器)中,并且我想让 html 成为 html,而不是 heredoc 文本。

谢谢

4

2 回答 2

0

你为什么不把 div 标签放在那里,而不是放在你的 php 函数中?如果你必须有受 PHP 影响的样式,我推荐一个 PHP 函数,它会吐出一个类<div class="<?php echo getClass();?>">..content..</div>

于 2012-10-25T21:58:24.560 回答
0

就像 Martin Lyne 提到的那样,这有点倒退,我猜这是一种奇怪的做事方式。可能更是如此,因为您故意不显示最终使用的全部范围。这是您的代码清理并变得更加理智。您有语法错误,并且 PHP 中不允许使用一些东西,例如您调用函数的方式。

<?php

function fancy_container ($contents_array) {

    if (!is_array($contents_array) || empty($contents_array)) {
        return '';
    }

    $output = '';
    $output .= '<ul>'.PHP_EOL;
    foreach ($contents_array as $content) {
        $output .= '<li class="special">'.$content.'<div class="other-specials"></div></li>'.PHP_EOL;
    }
    $output .= '</ul>'.PHP_EOL;

    return $output;

}

$contents = array();

ob_start();
?>

    <div class="whatever">hi there</div>
    <div class="whatever">hi there</div>
    <div class="whatever">hi there</div>

<?php

$contents[] = ob_get_contents();
ob_end_clean();
    ob_start();
?>

    <div class="other-junk">hiya</div>
    <div class="other-junk">hiya</div>
    <div class="other-junk">hiya</div>

<?php
$contents[] = ob_get_contents();

ob_end_clean();

echo fancy_container($contents);

?>

输出标记

<ul>
<li class="special">
    <div class="whatever">hi there</div>
    <div class="whatever">hi there</div>
    <div class="whatever">hi there</div>

<div class="other-specials"></div></li>
<li class="special">    
    <div class="other-junk">hiya</div>
    <div class="other-junk">hiya</div>
    <div class="other-junk">hiya</div>

<div class="other-specials"></div></li>
</ul>
于 2012-10-25T22:52:55.620 回答