带变量的 PHP 模板类?

发布于 2024-08-27 02:24:51 字数 849 浏览 9 评论 0原文

我想让我的新项目的开发变得更容易,并且我想要一个非常简单的模板引擎解决方案。我在网上环顾四周,一切要么太臃肿,要么让我感到畏缩。

我的 HTML 文件将如下所示:

<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>

显然,我想用我用 PHP 设置的内容替换 {PAGE_TITLE}{PAGE_HEADER} 。像这样:

<?php

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

?>

我会使用类似 str_replace 的东西并将替换的 HTML 加载到字符串中,然后将其打印到页面上?这就是我目前正在做的事情......有谁有任何建议或我可以做得更好的方法吗?

谢谢。

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.

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>

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!'
                         );

?>

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?

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

如此安好 2024-09-03 02:24:51

您当前的策略将会有效,而且非常简单。 str_replace() 高效且干净,您只需循环它即可将精确的标签匹配替换为变量内容。但是,缺点是您必须首先将所有模板加载到字符串中,这可能非常低效。

另一种非常相似的方法是您可以简单地使用 extract()。 Extract 将获取一组键/值对并在本地范围内创建变量。如果您 include() 同一范围内的模板,您的变量就可以使用了。

像这样:

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

您的模板可以只是常规的 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>

(显然,您可以使用短标签来减少模板的冗长,尽管出于兼容性原因我不喜欢这样做。)

那么您所要做的就是:

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

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.

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.

Something like this:

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

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.)

Then all you have to do is:

$pageElements = array(
                        'PAGE_TITLE' => 'Some random title.',
                        'PAGE_HEADER' => 'A page header!'
                     );
loadTemplate('file.phtml',$pageElements);
厌味 2024-09-03 02:24:51

您可能对 mustache.php 感兴趣。这是 Mustache 的一个非常轻量级的 PHP 类实现,

摘自自述文件的快速示例:

<?php
    include('Mustache.php');
    $m = new Mustache;
    echo $m->render('Hello {{planet}}', array('planet' => 'World!'));
    // "Hello World!"
?>

以及更深入的 示例示例——这是规范的 Mustache 模板:

Hello {{name}}
You have just won ${{value}}!
{{#in_ca}}
Well, ${{taxed_value}}, after taxes.
{{/in_ca}}

You might be interested in mustache.php. It's a really lightweight PHP class implementation of Mustache

Quick example taken from the README:

<?php
    include('Mustache.php');
    $m = new Mustache;
    echo $m->render('Hello {{planet}}', array('planet' => 'World!'));
    // "Hello World!"
?>

And a more in-depth example--this is the canonical Mustache template:

Hello {{name}}
You have just won ${{value}}!
{{#in_ca}}
Well, ${{taxed_value}}, after taxes.
{{/in_ca}}
篱下浅笙歌 2024-09-03 02:24:51

如果你想真正简单的话,PHP 本身就是一个模板引擎。只需使用 include()

file.phtml:

<html>
    <head>
        <title><?=$tpl['PAGE_TITLE']?></title>
    </head>
    <body>
        <h1><?=$tpl['PAGE_HEADER']?></h1>
        <p>Some random content that is likely not to be parsed with PHP.</p>
    </body>
</html>

code.php:

tpl = Array 
(
'PAGE_HEADER' => "This is the lazy way to do it",
'PAGE_TITLE' => "I don't care because i am doing it this way anyways"
)
include("file.phtml")

PHP itself is a template's engine if you want to be really simple. just use include()

file.phtml:

<html>
    <head>
        <title><?=$tpl['PAGE_TITLE']?></title>
    </head>
    <body>
        <h1><?=$tpl['PAGE_HEADER']?></h1>
        <p>Some random content that is likely not to be parsed with PHP.</p>
    </body>
</html>

code.php:

tpl = Array 
(
'PAGE_HEADER' => "This is the lazy way to do it",
'PAGE_TITLE' => "I don't care because i am doing it this way anyways"
)
include("file.phtml")
生生漫 2024-09-03 02:24:51

使用这个类
模板引擎支持块、循环、ifset(也适用于循环)和旋转。工作速度快。最适合中小型项目。

http://www.phpclasses.org /package/1216-PHP-Template-engine-blocks-loops-ifset-rotations.html

Use this class
Template engine with support for blocks, loops, ifset (also works in loops) and rotations. Works fast. Most suitable for small and medium projects.

http://www.phpclasses.org/package/1216-PHP-Template-engine-blocks-loops-ifset-rotations.html

梅倚清风 2024-09-03 02:24:51
function parseVars($vars, $file){

    $file = file_get_contents($file);
    foreach($vars as $key => $val){
        str_replace("{".$key."}", $val, $file);
    }

    echo $file;

}
function parseVars($vars, $file){

    $file = file_get_contents($file);
    foreach($vars as $key => $val){
        str_replace("{".$key."}", $val, $file);
    }

    echo $file;

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文