Click to See Complete Forum and Search --> : Template Parser


ShawnK
03-14-2005, 10:07 PM
I made this so that in my language files I can have included files as values!

here's the functions code:

<?php

include("lang/lang-english.php");

function parseTemplate( $fTemplateFile )
{
global $string;
if( file_exists( $fTemplateFile ) )
{
$fileContents = file_get_contents( $fTemplateFile );
foreach( $string as $tag => $value )
{
if( substr( $tag, 0, 2 ) == "__" )
{
if( file_exists( $value ) )
{
$includedFileContents = file_get_contents( $value );
$fileContents = str_replace( $tag, $includedFileContents, $fileContents );
}
else
{
echo "<b>Error: </b> Specified file(" . $value . ") not found!";
die( );
}
}
else
{
$fileContents = str_replace( $tag, $value, $fileContents );
}
}
return $fileContents;
}
else
{
echo "<b>Error: </b> Template file(" . $fTemplateFile . ") not found!";
die( );
}
}
?>


and here is what my language file looks like:

<?php
$string = array(
"{TITLE}" => "KurtzDownloadDB",
"{VERSION}" => "v. 0.1.1 BETA",
"{COPY}" => "Copyright © 2005 by Shawn Kurtz",
"__{CONTENT}" => "themes/default/_test.html"
);
?>


What it does is replaces all {TAGS} with their values. But, if a tag is prefixed like: __{TAG}, then the value of that tag will be included instead of assigned.

ShawnK
03-16-2005, 07:01 PM
please....anyone?

mrhappiness
03-17-2005, 09:44 AM
I wouldn't use global but call parseTemplate with two parameters (2nd can be reference if you want to)
This way you don't need to change the function in case you rename the var

You use { and } as delimiters for template vars and therefore should not use anything not inside these delimiters (although __ won't appear that often in normal text I guess)

What about {_CONTENT} instead of __{CONTENT}?

What about {include CONTENT} and replacing \{include (.*?)\} with $your_array['$1']?
(yes, that would be a regular expression)

Beside this:
if you include files first and than do the var replacment you are able to use {something} inside the included file as well, might be helpful sometimes


Anyway: I like your code. it's KISS (keep it short and simple) fast i guess and as long as you don't want to do anything special like formating the data stored in your array $string or have some blocks being repeated it's really good