問題描述
我最近寫了我的第一個 WP 插件,添加了一個用於將自定義 jquery 圖像庫嵌入到帖子中的短代碼。它主要是轉發一個很好的 HTML 塊,以及初始化所需的 javascript 。
但是,我不得不在 PHP 中構建 HTML 輸出,作為一個字符串。這種標籤湯總是讓我堅強,我習慣於使用 MVC 框架,它提供了幫助函數和部分模板來生成 HTML 。
需要管理大量動態構建的 HTML 或 JS 的插件作者的一般方法是什麼?
最佳解決方案
@Byran M. 我傾向於使用我經常看不到其他 WordPress 開發人員使用的兩個構造,這讓我很驚訝,但是我很喜歡他們。
Heredocs
您可以將大塊文本存儲為 heredocs 字符串,可能看起來像這樣,所以我可以存儲擔心混合單引號和雙引號:
$html=<<<HTML
<input type="{$type}" size="{$size}" id="{$id}" class="{$class}" value="{$value}" />
HTML;
請注意,變量可以作為數組傳遞給函數,然後可以以其他方式分配給 extract()。另請注意,我使用的大括號不是因為它們總是需要但它們使代碼更容易閲讀。 (當然,像 the_content()這樣的功能與 get_the_content()有很大的不同,WordPress 並不總是使這種編碼方式變得容易)
更重要的是,儘管可能與您無關,但如果我使用 hred,sql 等等,那麼我的 IDE PhpStorm 會執行語法注入,並且會給我自動填充和語法着色。
2.) 使用數組的字符串連接
我喜歡使用的其他成語是將內容收集到數組中,然後將數組中的 implode()。雖然我從來沒有對這個做過基準測試,但是它比我假設我知道重複的字符串連接是一個殺手,因為字符串越來越大 (如果有人知道為什麼這種方法不是更好,或者你知道一個更好的方法, ‘d 愛聽到反饋):
function my_get_form_and_fields($input_items) {
$html = array();
$html[] = '<form name="my_form" method="get">';
foreach($input_items as $input_item) {
extract($input_item);
$html=<<<HTML
<input type="{$type}" size="{$size}" id="{$id}" class="{$class}" value="{$value}" />
HTML;
$html[] = '</form>';
return implode("n",$html);
}
次佳解決方案
我沒有實際使用這個框架,但它提供的模板模型可能會吸引人。你可能想看看作者是如何設置的。
https://github.com/Emerson/Sanity-Wordpress-Plugin-Framework
Templates ========= Whenever possible, we should separate PHP from HTML. Within WordPress, you’ll see the two mixed together without apprehension. While this is often an “easy way” of doing things, it is almost never the “right way.” Instead, we should segregate the two, thus keeping our logic pure and our views dumb. For this purpose we have the $this->render(‘my-template’) method. A few examples:
// From within a method in our controller
$this->data['message'] = 'Pass this on to the template please';
$this->render('my-template');
// Meanwhile, in the /plugin/views/my-template.php file
<h2>The Separation of Logic and Views</h2>
<p><?php echo $this->data['message'];?></p>
第三種解決方案
檢查 PHP 的這個功能:
http://php.net/manual/en/function.ob-start.php
您可以將包含其中的 HTML 代碼的文件緩衝到 php 變量中。這將使其更加清潔維護。
所以你最終得到這樣的東西:
ob_start();
include('path/to/my/html/file.php');
$includedhtml = ob_get_contents();
ob_end_clean();
然後你可以只返回 $ includehtml 你需要它,它保持你的 html 內容不必在 php 字符串內部全部回顯。
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。