[英]PHP: How to create html container helper?
例如,我有一个具有非常特定格式的列表,我想一遍又一遍地放入不同的内容。
所以我可能有一个功能:
<?
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专家,所以我不熟悉正常的工作方式或局限性。 我知道如何使用红宝石产量做到这一点,但在php中不知道。
我只想将html内容注入到一个或多个容器中,并且我希望html是html,而不是Heredoc文本。
谢谢
为什么不将div标记放在那里,而不放在php函数中呢? 如果必须让样式受PHP影响,建议您使用一个PHP函数,该函数吐出一个类<div class="<?php echo getClass();?>">..content..</div>
就像马丁·林恩(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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.