例如,我有一个非常具体格式的列表,我希望反复提供不同的内容。
所以我可能有一个功能:
<?
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文本。
由于
答案 0 :(得分:0)
为什么不将div标记放在那里,而不是在php函数中?如果你必须有受PHP影响的样式,我建议使用一个PHP函数来发出类<div class="<?php echo getClass();?>">..content..</div>
答案 1 :(得分: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>