简体   繁体   English

带有变量的PHP模板类?

[英]PHP template class with variables?

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文件将是这样的:

<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. 显然,我想用我用PHP设置的东西替换{PAGE_TITLE}{PAGE_HEADER} 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? 我会使用类似str_replace东西并将替换后的HTML加载到字符串中,然后将其打印到页面中? 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. 谢谢。

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. str_replace()是高效和干净的,您可以简单地循环它以用您的变量内容替换精确的标记匹配。 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() Extract will take a set of key/value pairs and create variables out of them in the local scope. Extract将采用一组键/值对,并在本地范围内创建变量。 If you include() a template in the same scope, your variables will be ready to go. 如果在同一范围内include()模板,那么您的变量就可以运行了。

Something like this: 像这样的东西:

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

Your template could just be regular PHP. 您的模板可能只是普通的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);

You might be interested in mustache.php . 您可能对mustache.php感兴趣。 It's a really lightweight PHP class implementation of Mustache 它是Mustache非常轻量级的PHP类实现

Quick example taken from the README: 从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: 还有一个更深入的例子 - 这是规范的Mustache模板:

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

PHP itself is a template's engine if you want to be really simple. 如果你想要非常简单,PHP本身就是模板的引擎。 just use include() 只需使用include()

file.phtml: 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: 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")

Use this class Template engine with support for blocks, loops, ifset (also works in loops) and rotations. 使用此类模板引擎,支持块,循环,ifset(也适用于循环)和旋转。 Works fast. 工作得很快。 Most suitable for small and medium projects. 最适合中小型项目。

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

function parseVars($vars, $file){

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

    echo $file;

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM