[英]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.