1

我正在使用PHP進行模板化。我知道那裏有模板引擎,但我想要一個簡單的小項目。 這裏是我的問題:如何將模型層的消息或輸出集成到模板頁面

我的大部分產出都存儲在一個變量$內容並分配到模板在我的頁面的內容部分顯示

但有時我有回聲(「等等等等」)在我的模型[如異常情況下,查詢失敗],我想通過它到我的網頁。

問題是此輸出顯示在頁面之前,例如

$contents = "I want to show this"; 

$news = $news->getNews(); 

//concatenate 
$contents = $contents.''.[resultsfromnews] 

$template = new Template(); 
$template->content = $contents; //and so on 
$template->display(); 

如果$news->getNews()方法或它調用的方法回聲某物,例如, (「數據庫中的特定錯誤,異常),他們表現出$template->display()被稱爲

自定義錯誤信息/從getNews()通知顯示這裏之前網頁內容

普通網頁內容

的Lorem前ipsum dolor sit amet,consectetuer adipiscing elit,sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat。如果您有任何疑問,請聯繫我們的銷售代表。 DUIS AUTEM VEL EUM iriure悲在 hendrerit在vulputate velit埃塞 molestie consequat,VEL ILLUM dolore EU feugiat法無facilisis的vero性愛等accumsan等iusto奧迪奧dignissim魁blandit praesent luptatum zzril delenit augue DUIS dolore TE feugait法無facilisi。 南LIBER tempor暨soluta諾比斯eleifend選項congue虛無 imperdiet隆起ID

請幫我解決......那些輸出如何能成爲我的內容顯示的一部分。

我覺得這個問題可能會發生在所有流行的模板引擎(Smarty,Twig,phpsavant等) - 它是如何照顧的?

* 我一直在尋找了一段時間就知道它是如何工作的其他模板引擎 - 還沒有得到接近*

感謝

+0

如果你想爲你的項目提供簡單和小巧的東西,讓我建議你[小鬍子](http://mustache.github.com/)。 – hakre

+0

我以前見過但沒有時間去經歷。是否會處理從其他地方寫出的自定義消息 - 如問題 – codingbiz

+0

中提到的那樣是的,您可以分配變量。順便說一句,你也可以利用輸出緩衝,這可能就是你想要的嗎? HTTP:// PHP。net/manual/en/book.outcontrol.php – hakre

回答

1

要回答你的問題:

$contents = "I want to show this";  

ob_start(); 
$news = $news->getNews(); 
$buffer = ob_get_contents(); 
ob_end_clean(); 

//concatenate 
$contents = $contents.$buffer.''.[resultsfromnews] 

$template = new Template(); 
$template->content = $contents; //and so on 
$template->display(); 

然而,不應該在模型中迴應。在設置輸出之前拋出異常並捕獲它們會更好。

相關問題