Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

Template with optional PHP execution

by Flame (Deacon)
on Sep 01, 2001 at 19:21 UTC ( #109641=perltutorial: print w/replies, xml ) Need Help??

Name Change: From 'Simple Template' to 'Template with optional PHP execution'

Well, I've been hearing quite a bit about the 'FastTemplate' and other Template modules in several languages, (Perl and PHP in particular), and while I think it probably works quite well and does it's job properly, I have found that it can be a little too complex at times, especially when you do not need anything nearly so complicated.

I designed this template system because my website needed to have the template execute some PHP code within it, before being used by PERL as a template. Although it was designed to do that, the first method of use discussed here does not use PHP.

This is a quick tutorial on creating and using a simple template.

The Template:
All right, the first thing you need is the HTML or other code you will be making into a template. The following is just our example code.
<HTML> <HEAD> <TITLE>MyCode</TITLE> </HEAD> <BODY> <A HREF="mypage.cgi">Go to My Page!</A> </BODY> </HTML>

That should look like any other HTML document might since we have not started to make it into a template yet. Now, lets say we want the title to always be "MySite: page_name". We would change the code to something like this:
<HTML> <HEAD> <TITLE>MySite: $title</TITLE> </HEAD> <BODY> <A HREF="mypage.cgi">Go to My Page!</A> </BODY> </HTML>

Now, once that is done, lets say we want to make the link point to another page specified by a program. It is just as simple as before:
<HTML> <HEAD> <TITLE>MySite: $title</TITLE> </HEAD> <BODY> <A HREF="$pagelink">Go to My Page!</A> </BODY> </HTML>

Wherever we wish to include something that changes (The title, the page the link pointed to) we simply insert a Perl variable.

Here is another example, with a few more sections being determined by the program:
<HTML> <HEAD> <TITLE>MySite: $title</TITLE> $aditional_header </HEAD> <BODY BGCOLOR="$bground" TEXT="$text"> $main <BR><BR> <CENTER> $copyright </CENTER> <BR> </BODY> </HTML>

That example is a bit more complex, but it still works. Now, on to how to actually USE the template...

Using the Template:
Using the template is also quite simple. In the program that needs to use the template, simply assign values to each of the Perl variables you declared in the template. Here's an example:

Step one:
Insert this into a file named "" and place it in the same directory with the template file (I suggest naming the template HTML something simple... like "template.html" and placing them all within a "Template" folder if possible)
#Sub utemplate (use template) Call only when ready to print. sub utemplate { open(TEMPLATE,"/pathtotemplate/template.html") || die("Unable to ac +ess template: $!"); #Open the template file my @template = <TEMPLATE>; #Read it close(TEMPLATE); #Close it my $template = join("",@template); #Move it all into on +e variable $template =~ s/~/\\~/g; #Escape all ~ charac +ters already present. eval("print qq~$template~;"); #Process and print } 1;

Now we are ready to actually USE the template... this is a simple program which really doesn't do anything other than set variables and print the page:
#!/usr/bin/perl use CGI qw(:standard ); #Handy for printing header $CGI::HEADERS_ONCE = 1; #Make sure header is printed only once print header(); require "/pathtocommon/"; $title = 'First Templated Page'; $additional_header = qq~ <SCRIPT LANGUAGE="JavaScript"> alert("I'm a templated file!"); </SCRIPT>~; $bground = "#000000"; $text = "#ffffff"; $main = "Templating Rocks!"; $copyright = "(C) 2001 MyCompany"; &utemplate;

This simple little bit of code takes all the variables used in the template and evaluates them. Causing Perl to replace all the variables in the template... with the values of the variable in the program.

This means that the title line now reads <TITLE>MySite: First Templated Page</TITLE>

That was a brief explanation of how to create those types of templates. More little hints and tips can be found just below this paragraph.

Hints & Tips:
If you have a variable that you don't think you will need to change often (IE: The copyright variable in the example) then declare it within to mean what it will normally mean.

You can actually have Perl execute any PHP you have on the template by using the LWP module (or sockets) to get the file, here's an example of how to do that (New version of
use LWP::Simple; sub utemplate { my $template = get(""); $template =~ s/~/\\~/g; eval("print qq~$template~;"); die($@) if($@); } 1;

Try to keep all the template variables in the same case to prevent mistakes with $MAIN vs $Main or $main

This system actually works with PHP pages as well as Perl due to the similar use of variables.

Example Site:
Although it won't be obvious, this site uses this template system. (Ok, shameless plug... it's my site)

Final Notes:
I hope someone out there finds this useful. There may be a few mistakes in syntax as I wrote this just after I woke up. If you find one, please point it out and I'll try to have it corrected.

To use a $ in your template, you will need to escape it like you would in any perl string. \$ The same may apply to &, % and @.

Warning: This method does NOT work with use strict enabled... you may disable use strict around it however using no strict at the start and use strict once more at the bottom. To use 'no strict' you will need to place all of the code for the template into a block of it's own. Eg:
#!/usr/bin/perl use strict; use warnings; use CGI qw(:standard ); #Handy for printing header $CGI::HEADERS_ONCE = 1; #Make sure header is printed only once print header(); { no strict; require "/pathtocommon/"; $title = 'First Templated Page'; $additional_header = qq~ <SCRIPT LANGUAGE="JavaScript"> alert("I'm a templated file!"); </SCRIPT>~; $bground = "#000000"; $text = "#ffffff"; $main = "Templating Rocks!"; $copyright = "(C) 2001 MyCompany"; &utemplate; } #Continue with everything else you had to do

Other Templating Options:
HTML::Mason (Mentioned by wog )
Generic Search: Template

Replies are listed 'Best First'.
Re: Simple Template
by mirod (Canon) on Sep 01, 2001 at 19:56 UTC

    Did you have a look at Text::Template and HTML::Template? I don't know HTML::Template that well, but I know Text::Template and it does what you describe, and more, in a much more robust and powerful way. It is also just as easy to use.

    I definitely would _not_ re-invent an ad-hoc templating system when people like Dominus have already written it, and when it has been used for several years by thousands of users.

      I like the php-style of including files to the main template :3
Re: Template with optional PHP execution
by tachyon (Chancellor) on Sep 02, 2001 at 17:19 UTC

    I would have a look a HTML::Template, Template::Toolkit and HTML::Mason in rough complexity order. There are also tutorials on templating here on PM.

    Everyone writes a templating system at some time or another and (almost) everyone eventually comes to the realisation that one of the modular options does it better. All except the guys that wrote the modules of course :-)

    Welcome to Perl Monks BTW. cheers



Re: Template with optional PHP execution
by Flame (Deacon) on Sep 02, 2001 at 17:47 UTC
    Ok, I realize I probably did try to re-invent the wheel. And I probably didn't do the best job of it. So I'll accept a decision to delete this, if the other monks decide it's a waste of space. I really just wrote it because I couldn't think of any better way to get a template with PHP to execute... and I thought someone else might have the same problem.

    Regardless of weather or not this 'Tutorial' remains, I wish to thank wog and several other monks for helping me correct many errors in it.

    "Wierd things happen, get used to it"

    Flame ~ Lead Programmer: GMS

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perltutorial [id://109641]
[marto]: Sane Dots, chapter 13: ITIL never work :P
[marto]: sorry, bad pun of it'll :P
[Corion]: :-D
[Corion]: I think that ITIL is mostly to prevent people from doing harm to a system that basically runs unattended :)
[Corion]: Maybe you could reduce ITIL to a computer network, a man and a dog. The network runs the computations. The man is there to feed the dog. The dog is there to prevent the man from accessing the computers.
[marto]: from experience of this side of the fence, it's all about proving to people that you are ITIL compliant, then the client ignores logical processes anyway :P
[marto]: when you work on the outside, for a client, you can make them aware of the stupids, but they don' t always listen :/

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (12)
As of 2017-01-24 10:33 GMT
Find Nodes?
    Voting Booth?
    Do you watch meteor showers?

    Results (203 votes). Check out past polls.