RenderToHtml 视图文件并返回字符串?
我制作了一个小型 MVC 框架,但我需要我的视图类可以将页面作为字符串返回,但在此之前应用所有变量。这怎么能做到呢?
class View{
private $registry;
private $vars = array();
private $file;
public function __set($index, $value){
$this->vars[$index] = $value;
}
public function __construct($controller, $action){
$this->file = "Views/".$controller."/".$action.".php";
$this->registry = new Registry();
}
public function renderToHtml(){
try{
if(file_exists($this->file)){
foreach ($this->vars as $key => $value){
$$key = $value;
}
/** include $this->file; **/
//apply vars on file
return $html;
}else{
throw new Exception("No such View file");
}
}catch (Exception $e) {
echo '<h1>Caught exception: ', $e->getMessage(), "</h1>";
exit;
}
}
控制器:
public function indexAction(){
$html = new View('SomeController', 'htmlview');
$html->somevar = "blabla";
$this->View->fubar = $html->renderToHtml();
$this->View->render() //this will render the current action/view (index)
}
所以 htmlview 将是常规 indexView 的一部分
I made a small MVC Framework, but i need that my view Class can return the page as string but before that apply all the variables. How can this be done?
class View{
private $registry;
private $vars = array();
private $file;
public function __set($index, $value){
$this->vars[$index] = $value;
}
public function __construct($controller, $action){
$this->file = "Views/".$controller."/".$action.".php";
$this->registry = new Registry();
}
public function renderToHtml(){
try{
if(file_exists($this->file)){
foreach ($this->vars as $key => $value){
$key = $value;
}
/** include $this->file; **/
//apply vars on file
return $html;
}else{
throw new Exception("No such View file");
}
}catch (Exception $e) {
echo '<h1>Caught exception: ', $e->getMessage(), "</h1>";
exit;
}
}
Controller:
public function indexAction(){
$html = new View('SomeController', 'htmlview');
$html->somevar = "blabla";
$this->View->fubar = $html->renderToHtml();
$this->View->render() //this will render the current action/view (index)
}
so the htmlview will be a partial in regular indexView
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 输出缓冲
示例:
Use output buffering
Example:
看起来您需要获取文件内容并替换其中的所有变量。
Looks like you nee to get the file contents and replace all the variables there.