Become a fan of Slashdot on Facebook

 



Forgot your password?
typodupeerror
×
Perl Programming

Embed Perl With Mason -- Read All About It 37

autarch writes "Embedding Perl in HTML with Mason, written by Ken Williams and me, is now available at booksellers of distinction. Mason is a Perl-based templating system and application framework. The book covers Mason from the basics on up to extending the Mason core with your own subclasses. For more details check out our web site and the O'Reilly site. The latter includes the TOC and a sample chapter."
This discussion has been archived. No new comments can be posted.

Embed Perl With Mason -- Read All About It

Comments Filter:
  • Get it cheaper (Score:3, Informative)

    by RedWolves2 ( 84305 ) on Thursday October 24, 2002 @01:30PM (#4523989) Homepage Journal
    • Dosen't the url he gave have a referal code?

    • I used to think you just saw an opening to score a few bucks on a referral off of the slashdot community, but I just realized that's the entire reason [slashdot.org] you [slashdot.org] post [slashdot.org]. And those are just the times you've done it in the last week. Oh and here's another [slashdot.org].

      I notice you turn off your signature [slashdot.org] when your entire post is a referral scam.

      I couldn't imagine a sleazier way to make a few bucks. Disclose the fact that your tags have referrer links. It wouldn't hurt your "sales" and it would certainly help your karma. And I don't mean your slashdot karma...
  • Should be named 'shameless plug'.
  • Readability? (Score:4, Insightful)

    by glenstar ( 569572 ) on Thursday October 24, 2002 @03:16PM (#4524735)
    <disclaimer: Perl gives me a headache, but I respect it for what it is>

    I just don't understand how code like this (the first example in the Mason Developer Manual) is even remotely readable:

    <%perl>
    my $noun = 'World';
    my @time = split /[\s:]/, localtime;
    </%perl>
    Hello <% $noun %>,
    % if ( $time[3] < 12 ) {
    good morning.
    % } else {
    good afternoon.
    % }

    I know that Mason has a lot of wonderful things under the hood (the component caching mechanism is pretty swell) but I would rather shoot myself in the head than manage a large website with hundreds of pages that all looked like the above.

    • Re:Readability? (Score:3, Informative)

      by scrytch ( 9198 )
      Consider Template Toolkit instead. The above example transliterated looks like:

      [% noun = 'World' %]
      [% PERL %]
      # perl ugliness, but there may be a tt2 split op. note cache means nothing like mason's cache
      @{$cache->{time}} = split /[\s:]/, localtime;
      [% END %]
      Hello $noun,
      [% IF time[3] < 12 %]
      good morning
      [% ELSE %]
      good afternoon
      [% END %]

      Mind you, I'd have put it in variables in another block, so the message would look like:

      Hello $noun, $greeting

      I personally don't use the $foo syntax, and prefer [% foo %] instead, but TMTOWTDI in TT2. TT2's power just blows mason away, and it's not all that difficult to get it doing mason-like persistence things when you combine it with Tie::MLDBM.
      • I'm interested in your statement that "TT2's power just blows mason away". I use Mason (occasionally) and quite like it. I have looked at TT as well, and it also seems pretty powerful.

        So, what features and/or functionality in TT is so much better than Mason in your opinion?
        • Yeah, I'm pretty curious too. AFAIK, there really isn't anything you can do with one you can't do with the other. Some things may be a little easier in TT vs. Mason, and vice versa, and they each have their "special" features (a lot of people really like Mason's built-in caching features, for example).

          But I think they're pretty much comparable in terms of functionality.
        • Re:Readability? (Score:3, Informative)

          by scrytch ( 9198 )
          > So, what features and/or functionality in TT is so much better than Mason in your opinion?

          The internals of TT2 are amazingly hackable, and provide one of the most useful examples of OOP reuse. It's like a textbook study in design patterns that work. For example, it took me only a few hour's hacking to subclass one class (I forget the name, it's been a while) to create mason-like search behavior for [% INCLUDE %]. Just syntax-wise, TT2 tends to look cleaner -- you don't have to have weird looking noise like <% } > ending all your blocks. You can even change the delimiters from [% foo %], e.g. the metatext %%foo%%, mason's lt;% foo %> or anything else you want, within reason (the parser can get confused).

          Anyway, all those intangibles aside, TT2 is a complete language in its own right -- looks a bit like python, come to think of it -- so you can do even complex logic without embedding perl. When you do embed perl, you can simply 'print' in a perl block, and it will be output to the HTML (I wrote that part, though it's admittedly pretty trivial). In mason, you have to append to a string. If you need to really mess with the internals, you can embed [%RAWPERL%] blocks that are a straight eval. You can enable and disable PERL and RAWPERL blocks from the invocation, a nice way to set policy when using it in mod_perl.

          TT2 has INCLUDE not just for files, but for BLOCK definitions as well. You not only can define blocks, but functions and macros in the TT2 language. You can include arbitrary perl modules and use them in the TT2 language. You can take the output of any block and filter it with user-defined processors using unix pipe syntax. With [%WRAPPER%] you can do a reverse-include, taking the current doc and including it as the value of a magic variable in another document. Variables defined in the TT2 language have lexical scope, and you can choose to include a template in a new scope with [%INCLUDE%] or in the current scope with [%PROCESS%]. TT2 even has some amount of OOP, with [%VIEW%] constructs, which are sort of blocks on steroids. I still haven't completely wrapped my head around views, and they're still kind of primordial at this time, but they seem to be aimed at Mason's strength: components.

          Mason's component model is still superior to TT2, and I was writing a mod_perl system for TT2 that would have addressed that, but I haven't been too active with it lately (read: the year and a half or so). Mostly I've been pining for someone to port TT2 to python, actually. I don't see it as a contest of "Mason sucks, TT2 rules", I just have personal preferences, and would gladly like to see both systems giving each other healthy competition.

          BTW, Slash uses TT2, though not nearly to its full potential.
          • Re:Readability? (Score:2, Informative)

            by autarch ( 132719 )
            Uh, for almost every single thing you mention here there is a Mason equivalent. The sort summary:

            "amazingly hackable" - As of 1.10, it is pretty easy to subclass any one piece of Mason, including the part that implements Mason syntax.

            "complete language" - I don't consider this a desirable feature, so I'm happy to say Mason _doesn't_ match TT in this respect. But this is a question of style and what type of design you prefer, not power. TT is a complete language, but so is Perl, which Mason uses ;)

            Mason components are largely equivalent to defining subroutines/methods. Mason also has its own OO-ish system for defining component methods and attributes.

            With 1.10, we added a "component calls with content" feature that lets you apply filters to arbitrary chunks of content, and 1.14 included a feature for user-defined escaping mechanisms, so that's pretty well covered.

            In the end, I think the one you choose will have much more to do with the particular needs of your project, the people working on it, and which one fits your brain.

            But I would point out that there is really very little that one system does that the other _cannot_ do. Some things are a little easier in one versus the other, but both of them are full-featured enough to make pretty much anything possible.
            • > Uh, for almost every single thing you mention here there is a Mason equivalent.

              Being church-turing complete, there's an unlambda equivalent to everything I mentioned as well. Why don't you look at TT2 before you leap to the defense of something I'm not even trying to attack. I certainly looked at Mason when looking for things to improve about TT2.
              • feh, if there's one thing i'd rather jump on it'd be slash's inability to edit remove your own comments (.5e has a good compromise system for this). i'm not following my own advice, and haven't given mason a look recently. just mod my comment down or ignore it or something...

                really though, if i'm going to get into the land of web template engines again, it'll be writing custom taglibs for jsp. not my first choice of template engines, but it would have the advantage that i could just drop my taglibs into what everyone else is using, for better or worse.
            • Well, we're using mason because some of the things we wanted were easy in mason - caching, very modular components, allows pragmatic use of Perl snippets next to HTML fragments.

              And some of the newer features we'll be making use of soon.

              It's for an in-house web interface to obscure little bits of code (chemoinformatics/chemistry design/property prediction) that have been wrapped up to allow our 'normal' scientists to use them. Many people have produced web-style interfaces to research tools like this. Mason helped us produce this interface 18 months ago with very little resource (i.e. 1 software developer). We're now extending it with slightly more resource. I'm a very happy mason user.
      • You don't need a split, or the Perl code. You can do it all in TT2 language:
        [% noun = 'World';
        USE date;
        this_hour = date.format(date.now,'%H');
        %]
        Hello [% noun %],
        [% IF this_hour < 12 %]
        good morning
        [% ELSE %]
        good afternoon
        [% END %]
        See the Template Toolkit website [tt2.org] for more information. The TT2 language is simple enough to be taught to semi-non-programmers, yet powerful enough to do some serious damage. And hey, Slashcode [slashcode.org] uses it!
    • That code is virtually identical, except for some intricacies of syntax, to PHP or JSP.

      All embedded scripting code looks pretty much the same. Mason is no more or less readable than any of the others.
    • To be honest with you, other than perhaps understanding the regular expression, what's so difficult about it?

      The <%perl> section is perl code. Two variable assignments. @time is an array with the elements of the current time. <% %> encloses an expression, which is inserted into the HTML. % in the first column is Perl code, which compares the third element of the time array (which is the hour) to 12. The 'if' statement encloses two pieces of HTML.

      I use Mason and Perl every day, and I'm not sure where the confusion is. Is it just you don't understand Perl, or that you haven't used mixing a programming language with HTML? If the latter, I have to tell you that this is the ONLY way to go when you have complex web pages.

      Aside: the regular expression is actually kind of stupid, because you can just do "my @time = localtime" and the third element is the hour.

      • Re:Readability? (Score:3, Interesting)

        by glenstar ( 569572 )
        It's not confusion so much as just how, um... unpleasant the code looks. Using code delimeters like <% is bad enough, but with Perl you end up with lots of $, %, etc... to *me* very, very unreadable code. So, to answer your question: I am not a Perl fan. At all. That being said, I prefer templating languages that allow for very clean separation of logic and HTML (as one example, look at Skunkweb, skunkweb.sourceforge.net)... then again, I am a Python bigot.

        Just my opinion. Like I said in my original post, I think that the concepts behind Mason are very valid and well implemented, I just dislike the templating language.

        • Fine:
          Hello, <& /util/GetName &>.
          Good <& /util/GetTimeDesc &>.
          Better?

          The are a bunch of different ways to cleanly separate the code from the HTML.
        • Re:Readability? (Score:2, Informative)

          by autarch ( 132719 )
          One of the advancements in recent versions of Mason is the ability to (relatively) easily replace parts of the core system with your own modules. So if you loved everything about Mason but the templating language, you could replace the lexer (the class that actually parses components) and easily hook it into the system as a whole.

          For the book, I showed the beginnings of an implementation of a pure XML syntax. I wouldn't actually _use_ such a thing, but the point is that it's now a lot easier to bend Mason to your will.
        • Mason allows very clean seperation of logic and HTML.

          If I know that someone else is going to maintain the HTML, then I have one template with all the perl code, which calls the template with all the HTML code. The only thing I have to tell the HTML designer is to put <% $variable %> in the HTML where variables should appear, and if there is to be a repeated second, then <%method top> should wrap the top section, <%method table> should wrap the repeated section, and <method bottom> should wrap the bottom section. I've never had a problem with an HTML designer who can't understand this in about 30 seconds.

      • Re:Readability? (Score:2, Informative)

        by mobosplash ( 316006 )

        I use Mason and Perl every day, and I'm not sure where the confusion is. Is it just you don't understand Perl, or that you haven't used mixing a programming language with HTML? If the latter, I have to tell you that this is the ONLY way to go when you have complex web pages.


        Mixing a programming language with your html template is not the only way to go. Tapestry (http://tapestry.sourceforge.net/) and XMLC (http://xmlc.enhydra.org/) put no programming code in the html and Tiles (http://jakarta.apache.org/struts/userGuide/dev_ti les.html) uses a tagging system that is very html like. These are all Java based solutions.

        I've done a lot of the mixing approach, especially with PHP, but now I use Tiles and it is incredibly powerful and flexible.

        Templating approaches like Velocity and patTemplate (for PHP) have small amounts of code in the html but as sub language designed for more readability so they are easier to maintain than the above.
  • by jslag ( 21657 ) on Thursday October 24, 2002 @03:40PM (#4524927)
    I just spent 12 months developing a reasonably complicated website/webapp for my organization, using mod_perl & HTML::Mason. I wholeheartedly recommend Mason for perl-savvy web developers; it does a really nice job of providing powerful tools without creating a steep learning curve. As long as you know perl, of course. Very snappy performance, to boot. I should probably buy a copy of the book as a 'thank-you' to the writers, who, in addition to their substantial coding work, are timely and helpful on the relevant mailing lists.
  • I've heard about several 'put perl into HTML' tools now like ASP with perl and embperl but I never seem to like it.

    I'm now actively involved in WebGUI [plainblack.com] (a content management system / application server) and we are looking for a templating system to allow for easy costumisation of the display our 'applications'

    It just seems a lot more easy to embed HTML into perl than the other way round. Or maybe I should read this book?

    I tend to think that Mason is trying to be php with the easy integration of all those nice perl modules. I'm not sure that is the best way.

  • by turnerjh ( 271 ) <cturner@pattern.net> on Thursday October 24, 2002 @06:14PM (#4525927) Homepage
    Though it really depends on what kind of system you're trying to make, generally speaking, embedding any serious amount of code into code in a different language often becomes very difficult to maintain. For quick things, it's usually the easiest. For moderately complex things, it's usually a push either way. But for any sizeable website, especially one that is going to be maintained over an extended period of time by multiple people, keeping as much -separate- as possible is a better approach.

    Whether you use ASP, JSP, TT, Mason, .NET, or anything else, you likely will have a lot more going on than simply displaying some simple words, maybe wrapped in some kind of if statement or while loop. You'll need to do some kind of data lookup, perform some kind of transformation of that data, apply a few business rules, then, finally, spit it out in HTML. By far, it is easier to maintain code that isn't mixed with html; like wise, it's easier to maintain html that isn't mixed with code. Plus you then have the option of using that same code to manipulate the data differently, perhaps a GUI application, set of command line utilities, or under a different embedding technology. Decoupling presentation from logic is always a win as complexity increases.

    Mason is terrific technology, though, and I'm very glad to see a book dedicated to it finally on the market. It is especially good to finally see some quality documentation on application frameworks that run under mod_perl; before now, there wasn't much besides the excellent wrapmod [oreilly.com] book and the equally excellent mod_perl cookbook [modperlcookbook.org].
  • Template Toolkit (Score:3, Interesting)

    by tezza ( 539307 ) on Friday October 25, 2002 @11:16AM (#4530401)
    I don't use Mason. I use Template Tookit [template-toolkit.org].

    True separation of business and display logic.

    Do all your processing, calculating, searching, formulating, control flow in perl with no HTML to be seen. Whack all your data in a hash. Pass said hash to Template->process(). Then any [% variable %] text in the HTML looks in the hash. Every web designer worth their salt can deal with that. What is great too is that [% %] comes as ordinary copy in Dreamweaver et alia. They can see where it's going to go. This has its limitations though. Some designers don't grasp the concept of dynamically generated hidden fields to pass variables in a session stack. They tend to omit important tracking stuff.

    Also Templates [TT2 being the favourite] will generate your emails. Combined with the rather strenuous Text::Autoformat [cpan.org], you get freakin' nicely formatted text emails.

  • Holy crap (Score:1, Flamebait)

    by The Bungi ( 221687 )
    Perl is so fucking useless, I'm surprised anyone is writing "books" or whatever the fuck about it.

    I mean, c'mon guys. What's wrong with JScript.NET?

  • Embedding Perl in HTML with Mason, written by Ken Williams and me, is now available at booksellers of distinction.


    Do you think he chose to announce his book in this fashion because it was a slashdot submission or do you think the entire book is filled with grammar like this? Maybe he should have run this submission through his editor.

If mathematically you end up with the wrong answer, try multiplying by the page number.

Working...