Echoing variables in a template

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
MisterB
Forum Newbie
Posts: 5
Joined: Fri Sep 23, 2011 2:41 pm

Echoing variables in a template

Post 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??
Last edited by MisterB on Sun Oct 16, 2011 2:10 pm, edited 1 time in total.
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: Echoing variables in a template

Post 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).
MisterB
Forum Newbie
Posts: 5
Joined: Fri Sep 23, 2011 2:41 pm

Re: Echoing variables in a template

Post by MisterB »

Is there a way to echo variables that are in a file?
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Echoing variables in a template

Post by Christopher »

One way to do that:

Code: Select all

$str = addslashes(file_get_contents($filename));
eval("echo \"$str\";");
(#10850)
MisterB
Forum Newbie
Posts: 5
Joined: Fri Sep 23, 2011 2:41 pm

Re: Echoing variables in a template

Post 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\";");
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Echoing variables in a template

Post 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. .
(#10850)
Post Reply