PHP template class with variables?

笑着哭i 提交于 2019-12-03 15:03:24

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

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

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

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

scott
function parseVars($vars, $file){

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

    echo $file;

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!