Page 1 of 1

Echoing variables in a template

Posted: Sun Oct 16, 2011 1:36 pm
by MisterB
Hello,

This is really getting on my nerves :banghead:
I've created a template system for a simple script that I coded, I put variables that should be echo'd within the templates, like this:

Code: Select all

<title>{$page_title}</title>
</head>
<body>
{$message}
</body>
And then in the php file I did:

Code: Select all

include "link_to_file.tpl";
But it simply echo's the file content as a string... But when I do something like:

Code: Select all

echo "This is a message: {$message}";
it displays the message variable! (why??)

I don't want to add <?php echo and ?> around each variable that I want to display, I've seen a lot of templates where the programmers just wrote their variables in that format "{$variable}"

I've tried file() file_get_contents() functions but nothing works :dubious:

Can someone please help me??

Re: Echoing variables in a template

Posted: Sun Oct 16, 2011 1:55 pm
by Weirdan
{$variable} is a syntax for interpolating variables into a string literal (enclosed in double quotes).
file_get_contents() and friends return string value (not string literal).

Re: Echoing variables in a template

Posted: Sun Oct 16, 2011 2:08 pm
by MisterB
Is there a way to echo variables that are in a file?

Re: Echoing variables in a template

Posted: Sun Oct 16, 2011 9:49 pm
by Christopher
One way to do that:

Code: Select all

$str = addslashes(file_get_contents($filename));
eval("echo \"$str\";");

Re: Echoing variables in a template

Posted: Mon Oct 17, 2011 11:32 am
by MisterB
OMG it worked!!

The way you did that is genius, you execute the "echo $str" where $str is the file content (addslash'd) :)
Thank you :)
Christopher wrote:One way to do that:

Code: Select all

$str = addslashes(file_get_contents($filename));
eval("echo \"$str\";");

Re: Echoing variables in a template

Posted: Mon Oct 17, 2011 9:32 pm
by Christopher
Be warned that using eval() can make you code hackable. If you are getting that template from an untrusted source the it should be filtered and validated before it is saved and/or loaded. .