I am working on templating in PHP. I know there are templating engines out there but i want something simple for a small project. Here is my problem:
Most of my output are stored in a variable $contents and assigned to the template to display in the content section of my page
But sometimes i have echo("blah blah") in my Model [like in case of exception, query failure] and i want to pass that to my page.
problem is this output shows before the page e.g.
$contents = "I want to show this";
$news = $news->getNews();
//concatenate
$contents = $contents.''.[resultsfromnews]
$template = new Template();
$template->content = $contents; //and so on
$template->display();
if $news->getNews()
method or the methods it calls echoes something e.g. ('database specific error, exception), they show before the $template->display()
is called
Custom error information/notification from
getNews()
showing here before page contentNormal Page Content
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id
Please help me with a solution... how those output could be part of my content to display.
I feel this issue could occur with all the popular template engines out there (Smarty, Twig, phpsavant etc) - how was it taken care of?
*I have been searching for awhile to know how it works in other template engines - have not got close *
Thanks
To answer your question:
$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();
However, one should not be echoing within models. It is better to throw exceptions and catch them just before setting the output.