Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW

OUTPUT: inline or template_based?

by CodeHound (Beadle)
on May 28, 2002 at 09:48 UTC ( #169726=perlmeditation: print w/replies, xml ) Need Help??

Hi all,

I am adventuring in the world of perl and web based applications, and I stumbled upon a very important matter regarding which way HTML (or your output of choice) is to be printed: via inline PRINT (something with vars... ENDHTML is surely better) or via TEMPLATE reading, parsing and outputting?

ENDHTML example
$myvar= 'foo'; print <<ENDHTML; <html> <body> Todays variable is: $myvar </body> </html> ENDHTML

open $templatefile; $newfilecontent= &parse($templatefile, \@replacements); open $newfile; print ($newfile, $newfilecontent);

I've come to the conclusion ENDHTML printing is more CODE-WISE and maybe more practical to develop, but its surely not open to flexibility. On the other hand, the convenience of template parsing means lots of code for managing errors and exceptions...
Which are your personal ideas on the most PRACTICAL way to proceed?

Thanks in advance

Replies are listed 'Best First'.
Re: OUTPUT: inline or template_based?
by George_Sherston (Vicar) on May 28, 2002 at 10:41 UTC
    There are several advantages to templates (HTML::Template is my fave, and a popular choice), among which on emight include:
    • easy to cannibalise existing HTML
    • re-usable (bits that crop up in page after page can have their own, single, template)
    • easy to change "skins"
    • data hiding - pushes the formatting choices into their own space where you can forget about them
    • easier to handle situations where you've got lots of different things that you might output in the same format
    Having said that, for short and simple data output, I agree that the overhead in setting up the template (overhead in terms of that most important=to-optimise variable, developer time) sometimes makes one want to dump it straight into the code.

    In this case (as in so many others) is often the way to go, as its built in functions make on-the-fly html generation in the code a good deal quicker and more readably integrated with the rest of the code. Your example wd become:
    use CGI qw/:standard/; print header, start_html, "Today's variable is: ", $myvar, end_html;
    + n.b. that the more complex the html you are outputting, the more time and space the CGI functions become.

    When dumping large quantities of info into html tables, I felt the need of something like this, which you may also find useful.

    § George Sherston
Re: OUTPUT: inline or template_based?
by tomhukins (Curate) on May 28, 2002 at 11:09 UTC
    This issue has been discussed several times on Perl Monks. Try typing templating into the search box at the top of each page, and find out how to use Super Search. You might find for HTML output? useful. Templating works well when used as part of a model view controller architecture. Also, you might like to consider technologies like XSLT which is discussed in XSLT vs Templating?.
      Phew was it there stuff to read... however I have noted one post in particular which tells that the community is simply divided by which technique is better... and I sincerely could still not determine what fits best the common practice.

      Point is: I don't have experience on the subject, so I was interested in Monk's opinions to make up my mind before doing serious coding.

      As of now, I prefer inline code... most simply because I dont have still understood (nor found) practical examples of WHY templating IS better.

      To maybe enrich the concept some more... suppose that the templates need not be modified once the APP is deployed... wouldn't it be an unworthy effort to code for such use and open a vulnerability in the application?

      Many thanks everybody

        The main advantage of separating code according to the technology used is that different people can work on different parts without getting in each others' way.

        HTML developers can change the templates and Perl coders can change the programming without having to deal with unfamiliar technology.

        Inline code is fine if you are certain that all developers working on the project will be able to and have time to understand both the Perl and HTML. If there is any possibility that changes will be required in the future and you don't know who will make those changes, use a templating system. In practice, this happens on any successful project.

        Separating the programming logic (model), the HTML (view) and the page generation code (controller) allows developers to specialise in their own areas, makes code more robust and gives you the flexibility to add new or multiple front-ends in the future.

        Given how easy it is to incorporate something like Template::Toolkit or HTML::Template into your code, I can't see any reason not to. Typically, to create a template object, pass parameters, and output the HTML (or XML, or whatever you wish to output) takes less than 20 lines of code.

        As of now, I prefer inline code... most simply because I dont have still understood (nor found) practical examples of WHY templating IS better.

        I did it this way too. My client gave me a hunk of ugly HTML code. It produced some very pretty pages. My client is a HTML developer. She's very very happy to edit HTML.

        I thought I knew better. I rewrote the HTML into CGI functions and wrote all the functionality she was paying me for around that. When I looked at the pages they looked similar enough to me.

        I thought I was being clever. I knew nothing about HTML::Template at the time. I knew next to nothing about templating. I was only doing my 3rd year of a Software Engineering degree. I knew about data separation, but I didn't think of HTML as data.

        Then came the change requests. My client wanted the <TR> tag moved to here, this change, that change. Please remove the whitespace at this point as it breaks some browsers... Argh! She wouldn't touch my Perl code (which of course isn't all bad) so every single time she wanted the interface tweaked she called me. And of course I couldn't charge her because it was my fault!

        Heaven forbid should she ever want the page changed in a major way. I have now ripped out the top and bottom bits and let her template them, but what about all the little bits?

        Oh how I wish I'd used templates! Even simple ones that are just text files with REPLACE_ME tags in them would have been better.

        When people tell you that if you don't use templates you'll regret it, they're right. If you code your HTML in to your code using HERE docs then it's a _little_ easier for the HTML person to fix on their own, but then you can run into the double update problem. I've had that too (although with PHP):

        My client rings me and tells me that whenever she tries to load the page (on some pages) it seems to go into an infinite loop. I check the code, and she's right. For some reason $x-- doesn't work if $x is a float in PHP (so $x = 3.5; while($x > 0) { $x--; } won't ever stop).

        So I change it to $x -= 1; and tell her it's fine. She thanks me and rings me 5 minutes later to tell me that it's broken again. What? I check and it is broken again. I fix it again and it breaks again. What's happening? Ah! She's changing the HTML embedded in my code and uploading her version over my fixed version again and again. At this point I grumble about CVS and explain to her than when she's done with her fixing, it would be nice if she'd make my change on line y.

        Templating is really the only way to go. Even though it's a pain to learn and even though you think that the design is set and you won't ever, ever, ever need to redesign the webpage you're producing.

        Good luck


Re: OUTPUT: inline or template_based?
by simon.proctor (Vicar) on May 28, 2002 at 11:35 UTC
    If you don't use templates then half way through your project you'll wish you had. I've seen quite a few horror stories in the shops I've worked at and have seen them all dissapear one I managed to advocate HTML::Template to my manager.

    As mentioned in a node above, separation of display, logic (and data) will make your coding life much easier. You imply that using templates introduces some form of spaghetti into your code, frankly (IMHO) nothing could be further from the truth. Just try HTML::Template or the Template Toolkit in a project and you'll see for yourself.
      I think I didn't make myself clear.
      I did not want to write that TEMPLATING makes for spaghetti code.

      Mine was a SPAGHETTI example of what I meant for templating :)

      Thanks for the reply anyhow.
Re: OUTPUT: inline or template_based?
by Ovid (Cardinal) on May 28, 2002 at 14:43 UTC
Re: OUTPUT: inline or template_based?
by Aristotle (Chancellor) on May 28, 2002 at 15:26 UTC

    Your example does not really make a good case for templating. Simple variable substitution is not hard to do without templates. You run into trouble however once you try to dynamically generate tables, lists or such of unpredetermined size.

    In that case I find that inlining HTML actively promotes bad programming habits.

    I've seen far too often code where little bits of the output are produced by prints strewn throughout various loops and subroutiness here and there and everywhere. Needless to say one change to the layout that requires tags to be changed in concert between several such parts may require hours of scrambling around.

    But just a simple change of look isn't even the biggest problem. The real problem with such a style is that you cannot change the alignment of your output without jumping through major hoops. That is, if you had a 2-column vertical output, and you want to change it to a 2-row horizontal output f.ex, you have to change the entire code's logic around to accomodate the new style. UGH. Don't go there.

    With templates on the other hand, what your code does is collect all the data into a well-defined data structure, and then hands it all over to the templating mechanism. Even if there are major changes to be made to the way the output is produced, your code's logic never needs touching.

    That's why you should use templates. I find that I now use templates for even the simplest of CGIs if the markup I'm going to produce isn't completely static.

    Makeshifts last the longest.
      Makeshifts last the longest.

      Indeed, and this tagline may be noting another reason to use Templates... :) Now that I'm learning more and more about templating, it seems to me that I, and probably others, have inlined HTML, etc., as an expeditious solution - that later became the nightmare you described.

Re: OUTPUT: inline or template_based?
by abstracts (Hermit) on May 28, 2002 at 14:31 UTC
    Please don't inline HTML, SQL, or anything that is not perl.

    In my current job, I need to clean up (rewrite) 400,000 lines of Perl/SQL/HTML/Mail/... in 800 or so CGI scripts. You can just imagine how horrifying it is. The guy who wrote it initially had run away with his life. Anyways...

    I'm contemplating the idea of having each section of the program output in plain simple XML and then do the transformations to HTML/PDF/Anything using XSLT or any other XML templating tool. That way, I'd have total separation between logic and presentation.

    Hope this helps,,,

      I agree with everything, except for separating SQL. I think this is not practical at all. There's no need to do it, really, as you are the man who writes both SQL and perl, usually. Perl glue code is as a rule tightly dependent on SQL and you don't want to change one of them without at least reviewing the other.
Re: OUTPUT: inline or template_based?
by maverick (Curate) on May 28, 2002 at 16:26 UTC
Re: OUTPUT: inline or template_based?
by CodeHound (Beadle) on May 29, 2002 at 13:56 UTC
    Many, Many thanks everybody.
    Even if I see it has been discussed before, I think the resumè here is in some way more complete than what I read on the other topics on the subject, of course thanks for that people who cited their experiences.

    So if I got it correctly:
    Templating is the choice, simply because with the little development effort required with the many templating mods one just saves himself MANY headaches for maintaining and deploying the applications developed.
    I still have some doubts regarding the 'security' issue with templating (arbitrary SCRIPT code in the html or things like that) but I believe just MIXING maybe the two output techniques will give the best results?
    Anyhow, I'll now dive into templating!
    Thanks again people!

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlmeditation [id://169726]
Approved by MeowChow
Front-paged by jarich
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (3)
As of 2022-11-30 20:31 GMT
Find Nodes?
    Voting Booth?