The following is a short subroutine that lets you implement a rudimentary template system, where a word specified in square brackets is replaced by the return value of that method call in a given object.

Caveats:

This will probably become a module in the future, with added safety features and customizability. But if you need to handroll a quick-and-dirty template (such as reading fields from a database and sending E-mails), this can get you started.

sub apply_template { my ($object, $template) = @_; $template =~ s/\[(\w+)\]/$object->$1/emg; return $template; } # Example usage: my $template = "Hello [name]. You are [age] years old!"; # We assume there is an object called "Person" with # accessor methods for "name" and "age". my $monkey = new Person (); $monkey->name("Maybelle"); $monkey->age(4); my $message = apply_template($monkey, $template); # prints "Hello Maybelle. You are 4 years old!" print $messane, "\n";

Replies are listed 'Best First'.
Re: A quick and dirty template system
by merlyn (Sage) on Sep 13, 2001 at 12:34 UTC
    Please. Don't.

    I don't know why it's some "rite of passage", but it seems that everyone goes out and (re)writes their own templating system in Perl.

    There are already something like 36(!) of them in the CPAN.

    Please study them first. If none of them do what you want, feel free to write your own, or better, contribute code patches to the one that is closest to what you want.

    The world does not need you wasting your time reinventing this wheel for the 37th time. There are many more urgent things to do. If you're really looking for something to tackle in your spare time, ask me... I've got a pile of stuff on my todo list.

    -- Randal L. Schwartz, Perl hacker

      There are already something like 36(!) of them in the CPAN.

      Perhaps that's got something to do with why everyone wants to write his own. I certainly thought of it (and then thought better). Because if there are 36 to choose from (A) it opens up the hope of getting a perfect template, which is in fact a doomed hope unless one writes one's own; (B) why should I think mine won't be as good as number 30 at least? (C) how the devil do I choose one of them - and by the time I've assessed all thirty-six I could have written my own.

      My point is, I would be very glad to hear of any other monk's experience with one or more of the different systems, particularly if capable of comparing one with another. That way my choice of one out of thirty-six would be a little less random...

      § George Sherston

      Don't worry. This is just a quick hack. Literally a couple of lines of code.

      I'm not about to implement a new template system, though if it seems unique enough and can remain simple, well, it might grow into something in the distant future...

      Yet I can think of one very good reason why I might prefer a simple templating sub like this one to the more advanced modules on CPAN.

      My ISP lets me run Perl scripts but does not allow me to install modules. To install one of the CPAN modules I would need to:

      1. find one that did not have C code in it
      2. then experiment with creating the proper subdirectories so the various module components could all locate each other at runtime.

      Isn't it better to run a simple script like this that does what I want? Indeed, I intend to try this one out.

      I truly believe that Merlyn is brilliant. I read his columns. I buy his books. I vote for his nodes on this site.

      But we are not all Merlyn. I am running on an inexpensive web server that only has limited capabilities. CPAN modules are out of my league at home, although I use them at work every day.

Re: A quick and dirty template system
by scott (Chaplain) on Sep 19, 2001 at 22:32 UTC

    Please, do.

    True, it is a common rite of passage. True, there are dozens available on CPAN, true, you should study those. Odds are you're not going to beat something like Text::Template

    But false, writing your own is not a waste of time. It's a great way to focus on the issues involved in what a template system should do and on what you really want it to do.

    I don't think there is any substitute for learning by doing. Studying the derivation of Fermi's Golden Rule #2* is, speaking from direct experience, far less enlightening than closing the book and deriving it starting from a blank sheet of paper.

    All, IMHO, of course.

    scott

    * Roughly, Fermi's Golden Rule #2 is a general expression for the transition rate of a quantum system, per unit time, from some initial state to some final state, where the situation is complicated enough to require being modeled as a perturbation of some more simple situation. Got all that? Pop quiz tomorrow. :)

      I don't think there is any substitute for learning by doing. Studying the derivation of Fermi's Golden Rule #2* is, speaking from direct experience, far less enlightening than closing the book and deriving it starting from a blank sheet of paper.
      And part of learning is studying prior art, which is apparently lacking in practically all of the "templating systems" I've seen.

      Listen, I really wouldn't mind someone saying "I've studied Template, and Text::Template and HTML::Template and Text::MetaText and the PerlFAQ entries and ..., and now I want to write my own, because this feature is lacking and that feature is broken". But nobody has ever done that that posts "here's my templating system, and it's simple for now, but I'm adding $FEATURE_X later". They just go off and start implementing. You think Perl would have been where it is had Larry not carefully studied Awk and Sed and other tools before he started?

      This is why I grumble about reinvention, and templating systems in particular. Do not attempt to reinvent the wheel without studying the fallacies of those who have gone ahead, or else you are wasting human potential in a larger sense. This isn't just about you. It's about humanity.

      -- Randal L. Schwartz, Perl hacker

        Do not attempt to reinvent the wheel without studying the fallacies of those who have gone ahead,

        or, as i like to say, "Don't reinvent the wheel unless you're going to make it round."

        .

        And part of learning is studying prior art ...

        Sure. I think that was implicit in my example.

        ... "here's my templating system, and it's simple for now, but I'm adding $FEATURE_X later". They just go off and start implementing. ... Do not attempt to reinvent the wheel without studying the fallacies of those who have gone ahead, or else you are wasting human potential in a larger sense. This isn't just about you. It's about humanity.

        I think we're talking about multiple issues while treating them as one. Writing your own first-order templating system and then posting it madly across the world is certainly a waste of time for everyone. If you thought 36 to choose from was bad, consider if all the templating systems ever designed were enshrined in CPAN. There'd be 360,000 of them. This is obviously not good. It's the treating of what is essentially a learning script as something of value to the community that's a bad idea. Putting anything that doesn't deserve it on CPAN, etc. is bad and does indeed 'waste human potential'.

        This does not mean that the effort that went into the creation of templating system #361,054 was in any way wasted. Reinventing the wheel is good for the understanding of the reinventor and far from a waste of anything, assuming the job was done as a learning experience.

        So I agree and disagree with you. Yes, don't post your templating system please (unless it's better than the competitors)! We've got enough. But no, don't not write your own. By all means, write it ... if you write it as a learning experience, as a way to understand what a templating system is like, as a way to experiment with code that runs code (like TT2), as a way to experiment with an easily understood problem that can be implemented in varying degrees of depth and sophistication.

        On a more philosophical note, since you started talking about all humanity, excessive study of that which has gone before can diminish creativity as well as increase it. Certainly, one learns many hard wrought lessons much easier that the original learners. But one also comes to be infected with their world views. It is not always possible to know what is good practise and what is thought to be good practise, especially when one isn't very practised oneself.

        One should strike a balance between paying attention to the vast body of collected knowledge and generating one's own. A great deal of the collected wisdom of the ages is wrong - for the obligatory example I give you the Great Fluxion/Infinitessimal Debate, which was thought to be settled by Bishop Berkeley in the 16th(?) century. Turns out he was wrong and it took until 1960-something to demonstrate. Up until that time 'those in the know' were quite convinced he was right.

        scott
        -----------------------------------------------------
        Do not depend on Eternal Mathematical Verities for your foundations. They change.

        P.S. Wow! My first negative-point post! Cool!