PHP模板类与变量? [英] PHP template class with variables?

查看:115
本文介绍了PHP模板类与变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让我的新项目开发更容易,我想要一个裸骨骼非常简单的模板引擎解决方案。

I want to make developing on my new projects easier, and I wanted a bare bones very simple template engine solution. I looked around on the net and everything is either too bloated, or makes me cringe.

我的HTML文件会是这样:

My HTML files will be like so:

<html>
    <head>
        <title>{PAGE_TITLE}</title>
    </head>
    <body>
        <h1>{PAGE_HEADER}</h1>
        <p>Some random content that is likely not to be parsed with PHP.</p>
    </body>
</html>

显然,我要替换 {PAGE_TITLE} {PAGE_HEADER} 我用PHP设置的东西。像这样:

Obviously, I want to replace {PAGE_TITLE} and {PAGE_HEADER} with something I set with PHP. Like this:

<?php

    $pageElements = array(
                            '{PAGE_TITLE}' => 'Some random title.',
                            '{PAGE_HEADER}' => 'A page header!'
                         );

?>

我会使用 str_replace 并将替换的HTML加载到字符串中,然后打印到页面?这是我现在正在做的路径...有谁有任何建议或方式我可以做得更好?

And I'd use something like str_replace and load the replaced HTML into a string, then print it to the page? This is what I'm on the path towards doing at the moment... does anyone have any advice or a way I can do this better?

谢谢。 p>

Thanks.

推荐答案

您当前的策略会奏效,非常简单。 str_replace()是高效和干净,你可以简单地循环它来替换与变量内容的精确标记匹配。但是,缺点是你必须首先将所有的模板加载到字符串中,这可能是相当低效的。

Your current strategy will work, and is pretty straightforward. str_replace() is efficient and clean, and you can simply loop it to replace exact tag matches with your variable content. However, the drawback is that you have to load all your templates into strings first, and that can be pretty inefficient.

一个非常相似的替代方法,你可以简单地请使用 extract()。提取将采用一组键/值对,并在本地作用域中从中创建变量。如果你 include()在同一范围的模板,你的变量将准备去。

An alternate method that's very similar, is you can simply use extract(). Extract will take a set of key/value pairs and create variables out of them in the local scope. If you include() a template in the same scope, your variables will be ready to go.

this:

function loadTemplate($template,$vars)
{
    extract($vars);
    include($template);
}

您的模板只能是普通PHP。

Your template could just be regular PHP.

<html>
    <head>
        <title><?php echo $PAGE_TITLE ?></title>
    </head>
    <body>
        <h1><?php echo $PAGE_HEADER ?></h1>
        <p>Some random content that is likely not to be parsed with PHP.</p>
    </body>
</html>

(显然你可以使用短标签来减少模板的冗余, )

(Obviously you could use short tags for less template verbosity, although I prefer not to for compatibility reasons.)

那么你所要做的就是:

$pageElements = array(
                        'PAGE_TITLE' => 'Some random title.',
                        'PAGE_HEADER' => 'A page header!'
                     );
loadTemplate('file.phtml',$pageElements);

这篇关于PHP模板类与变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆