[英]Simplest/quickest way of 'rendering' view file in PHP
Lets say i have a simple view file called MyView.php: 可以说我有一个名为MyView.php的简单视图文件:
<!DOCTYPE html>
<html>
<head>
<title><?=$title?></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<?=$cotent?>
</body>
</html>
And i have a method in my code called render()
: 我的代码中有一个方法称为
render()
:
<?
function render($data)
{
}
?>
I need to call MyView.php
from there and pass $title
and $cotent
variables to it. 我需要从那里调用
MyView.php
并将$title
和$cotent
变量传递给它。
I know that there is a way of doing that by just replacing <title><?=$title?></title>
to, lets say, <title>{TITLE}</title>
and then in render($data)
just load MyView.php
into variable and with preg_replace()
replace all {BLAH}
with $blah
. 我知道有一种方法可以通过将
<title><?=$title?></title>
替换为<title>{TITLE}</title>
然后在render($data)
替换。只需将MyView.php
加载到变量中,并使用preg_replace()
将所有{BLAH}
替换$blah
。
Is there any other simple way of doing this? 还有其他简单的方法吗?
Frameworks shall not be used. 不得使用框架。 Everything from scratch.
从头开始的一切。
Yes. 是。 From my personal library:
从我的个人图书馆:
function renderTemplate($tmpl, $__vars=array()) {
extract($__vars, EXTR_SKIP);
include($tmpl);
}
renderTemplate("MyView.php", array( "title" => "My Title", "content" => "My Content" ));
If you wanted to render to a string, you could modify it a bit: 如果要呈现为字符串,则可以对其进行一些修改:
function renderTemplateToString($tmpl, $__vars=array()) {
ob_start();
extract($__vars, EXTR_SKIP);
include($tmpl);
return ob_get_clean();
}
Note that renderTemplate()
needs to be kept in its own function, even if you're only calling it once: it's using the function's variable scope to keep template variables separate from other variables. 请注意,即使只调用一次
renderTemplate()
需要保留在其自己的函数中:它使用函数的变量作用域将模板变量与其他变量分开。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.