Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Model-View-Controller: Template Toolkit vs. XSLT

by kvale (Monsignor)
on Oct 14, 2004 at 16:12 UTC ( [id://399245]=perlmeditation: print w/replies, xml ) Need Help??

The Model-View-Controller (MVC) pattern separates an application into three components:
  • Model - maintains the state of the program, contains the data store
  • View - creates a 'view', that is it transforms the model data into a form accessible to the user
  • Controller - implements a user interface that allows the user to interact with the model
The MVC pattern is an updated version of the old adage that computer programs come in three parts: input, processing, and output. It is a nice way to describe the high-level architecture of an application because Views and Models naturally separate form from content. Separating form from content usually leads to cleaner code and greater flexibility.

For a future web application, I am meditating on the best approach to take for the view and model. There are two general approaches I am looking at.

The first is a traditional perl templating scheme. The model would be a flat file or relational database, bound to a perl program through DBI. The view would consist of a set of template documents that would transform data to various formats (HTML, plain text, CSV, etc.) using, for example, Template::Toolkit.

The second approach is to build an XML application. The model stores data in an XML format and is accessed directly, or perhaps using XML::LibXML. The view would consist of a set of template documents that would transform data to various formats (HTML, plain text, CSV, etc.) using the XSLT language via, e.g., XML::LibXSLT.

I have little experience with either templating scheme, and I am seeking advice on the pros and cons of these two approaches. I understand that the subject of XML vs. relational databases is contentious. Let's assume that I am comfortable implementing either variety. and that the database will be small enough that performance considerations will not be foremost in the design. Also, if performance becomes a problem, I could create an XML wrapper around DBI results. So the comparison becomes that of a perl templating language vs. XSLT.

Some questions pertaining to the comparison are

  • I'd like the code to be maintainable after I leave. Is it reasonable to expect novice programmers to be able to learn to manipulate and modify Template Toolkit templates? What about XSLT?
  • XSLT seems like a cool language in theory, but how is it in practice? Does it DWIM, or is it fussy and frustrating?
  • One aspect of XML/XSLT I like is that they are language neutral. Once the docs and templates are written, they can be processed in any number of languages: Perl, Java, C, C++, Python, etc. On the other hand, Perl and associated templating systems are in widespread use and not going away any time soon, so perhaps language neutrality is not so important?
  • Associated with XSLT is XSL-FO, an XML formatting language. Is XSL-FO commonly used as part of the transformation process?

-Mark

  • Comment on Model-View-Controller: Template Toolkit vs. XSLT

Replies are listed 'Best First'.
Re: Model-View-Controller: Template Toolkit vs. XSLT
by dimar (Curate) on Oct 14, 2004 at 22:11 UTC
    answering your questions

    Q: reasonable for novice programmers? A: XSLT (depends); Perl(depends); T::T(good bet).

    Q: How is XSLT in practice? A: See below for more info.

    Q: Is language-neutrality an XSLT advantage? A: No. Any XSLT 'neutrality gains' are illusory when you consider the differences in parsers (eg XALAN, SAXON, msxsml.dll (various versions), msft "dotNet", perl et al..) and difference in coding styles (which affects every programming language, not just XSLT) and the inevitable "turf battles" and "politics" of it all. Forget "language neutrality", its a marketing phrase. I've used each of the systems you specified, and have (or at least had) a particular affinity for each of them. Here then is one person's opinion.

    The short version is this. Avoid XSLT unless you know *exactly* what you're getting into ahead of time. It is not pretty. Use T:T if you have to work with non-technical people on your production team. Use Perl if you have a professional coding style that is eyeball friendly to whomever may inherit your code (thus bypassing the pervasive stigma that some hold against perl). This of course presumes you have no constrains re: technical proficiency; and no vendors or language zealots influencing your decisions.

    By the way, the reason all of this is relevant on a perl website is because nearly *every* criticism of XSLT that follows is the diametric opposite of perl. In other words, everywhere XSLT gets it wrong, perl gets it right.

    one person's biased (but well-founded) opinion

    When XSLT (actually XSL) first came out in the last millenium, you might say I was an eager and avid "early adopter". Having had favorable experience with perl templating (and templating tools in general), the assumption was that XSLT would be a versatile transformation and templating system: "just like perl, but with the structure of XML".

    That assumption was dead wrong.

    Don't get me wrong ... no software is perfect when it first comes out, but the design and direction of XSLT have absolutely convinced me that its principle advocates designers rarely (if ever) actually *use* it themselves for routine tasks. Certainly not as much in comparison to the principle advocates and designers of Perl, or even Template Toolkit for that matter (both of which have advantages and are worth learning).

    XSLT "pros"

    • XSLT is prevalent, and has the marketing-friendly kewl name that starts with the letter "X"
    • XSLT is good if you are selling books, software, certification and courses in XSLT
    • XSLT is good if you are a hobbyist who enjoys working with it for its own sake
    • XSLT is good if you had a role in designing it
    • XSLT is good if it keeps you employed

    XSLT "cons"

    • "XSLT is not intended as a completely general-purpose ... language" (see http://www.w3.org/TR/xslt) but people use it that way anyhow.
    • XSLT appallingly re-invents the wheel for the most rudimentary programming concepts (eg functions, loops, and variables). Moreover, the wheels are *all* square.
    • XSLT assumes too much, is too verbose, and too disjointed to be tolerable after the initial novelty wears off, which will be fast, unless you reap one of the "pros".
    • XSLT will have you searching for hours on how to do things that the XSLT designers tried to 'over engineer'
    • XSLT has too many 'reserved character sequences' that make it a pain to actually write code
    Print Hello World ten times

    For a real-world comparison, here are some snippets of code. DISCLAIMER: These are old code snippets, and may not reflect the optimal way to get the job done. They are just here to give a general idea.

    ### perl example print q© Hello World! ©for(1..10);
    ... next ...
    [%# Template Toolkit Example %] [% FOREACH [ 1 2 3 4 5 6 7 8 9 10 ] %]Hello World! [% END %]
    ... next ...
    <!-- XSLT example --> <!-- [..snip.. some stuff taken out for brevity] --> <xsl:call-template name="SayHelloTenTimes"> <xsl:with-param name="i">1</xsl:with-param> <xsl:with-param name="count">10</xsl:with-param> </xsl:call-template> <xsl:if test="$i &lt;= $count"> Hello world!! </xsl:if> <xsl:if test="$i &lt;= $count"> <xsl:call-template name="SayHelloTenTimes"> <xsl:with-param name="i"> <xsl:value-of select="$i + 1"/> </xsl:with-param> <xsl:with-param name="count"> <xsl:value-of select="$count"/> </xsl:with-param> </xsl:call-template> </xsl:if> <!-- [..snip..] -->

    MVC is a great model to follow, but I wouldn't want to try to implement it using XSLT, not unless you want to buy my book on how to do it ;-)

      You forgot the biggest problem with XSLT. That is, that it is clearly trying to be Lisp (just look at all those brackets!) but without the readability or power of Lisp.

      From taking one brief look at some XSLT code at a previous job, I can state with absolute certainty that use of XSLT is always wrong. To parse and run XSLT you need a more capable, easier to use programming language to be available anyway, so why not use it instead.

        That is, that it is clearly trying to be Lisp (just look at all those brackets!) but without the readability or power of Lisp.

        I think there's a fundamental difference here. LISP looks like that because it has to look like that. It's a direct consequence of being minimalistic and functional. XSLT looks like that because the designers thought that XML is Good. There isn't an underlieing, theoretical reason why XSLT has to be implemented that way, as there is with LISP.

        "There is no shame in being self-taught, only in not trying to learn in the first place." -- Atrus, Myst: The Book of D'ni.

•Re: Model-View-Controller: Template Toolkit vs. XSLT
by merlyn (Sage) on Oct 14, 2004 at 17:40 UTC

        Because Maypole has lots of problems that need to be fixed, like:

        • abysmal error handling and recovery (mostly inherited from UNIVERSAL::require)
        • Bad documentation
        • Bad extensibility as soon as more than one object is involved in one action
        • Bad logging infrastructure, ranging from nonexisting logging to wildly spewed warnings that can't be disabled
        • ...

        Many of these things are being worked on, by sri and others, but I wouldn't use Maypole in a setting where there is a client that pays for a working project that goes beyond beerdb in complexity.

Re: Model-View-Controller: Template Toolkit vs. XSLT
by Joost (Canon) on Oct 14, 2004 at 17:12 UTC
    I mostly agree with Corion that all templating systems suck and that XSLT sucks even more. People should not be made to code in XML.

    The thing I like the least about T::T is that it's slow and bulky - it's great if you want to make a lot of static files from complex templates, but IMO too slow for high-performance dynamic stuff. Also, having a complex templating system will probably bite you if you want to do MVC - programmers will tend to put too much logic in the templates, instead of in the model or controller classes. It's probably better to use a simpler templating system in this case.

    As for the controller part, there are modules - most famously the Maypole system and CGI::Application. I personally think that Maypole is doing too much (like Template::Toolkit) and links to too many modules I don't like/want - I'd recommend CGI::Application, it's much simpler and runs anywere.

      TT is slow? Compared to what? The only benchmark I know of shows it running at about the same speed as other popular Perl templating tools: http://www.chamas.com/bench/
        Snails are still slow, even when you compare them to slugs.

        What I dislike about TT isn't TT, but its fanboys. They claim that it allows you to seperate content from presentation from logic and that nothing else in perl does. What rot! Wanna display a table of data? You need logic in the template to loop over the data. Wanna display an arbitrarily sized table with arbitrary headings? You need a *lot* of logic in the template.

        The fanboys also argue that TT is easy for non-programmers to use. Sorry, but my experience differs. I wrote some nice functional templates which worked, handed them over to a designer to make pretty (and bear in mind that TT is alledged to be designer-friendly), and he promptly broke them all.

        Given that you can't get away from putting logic in the template, why bother inventing a whole new mini-language, when you could just use perl? The fanboys say that that means you put too much code in the template. Not true, unless you're an idiot. Perl has these things called "modules".

        Having said all that, I do use TT. For *some* jobs, it's the right tool. For other jobs I use it grudgingly because it's the company standard and it at least has the advantage of being well known.

      I've never seen the point of CGI::Application. What, exactly, does it do that a giant if/elsif/else statement doesn't? Nothing, from what I can tell, aside from introducing another dependency, like what you criticise Maypole for.
        CGI::Application does many other things than "a giant if/elsif/else statement" -- and it doesn't even really do that. (It implements a hash-based dispatch table that maps a query string to a method; if no match is found, it uses a default as specified.)

        What does CGI::Application do?

        • It provides a framework for developing re-usable, customizable application classes. Simply use the class, pass some metadata (in the form of a hash) to the constructor, and run() it
        • It provides a sane framework for developing applications; each screen gets a run mode, and each run mode gets a method -- CGI::Application-based classes are incredibly consistent and easy to debug because it's easy to determine what piece of code is executed when (look at the dispatch table instead of trying to scan through "a giant if/elsif/else statement").
        • It provides a means for wrapping a number of applications under a site-umbrella, through it's various cgiapp_*() hook methods. Using these, you can create a superclass that does security checks, places final application content in a sitewide template, and creates customized navigation and sidebars -- but still retain the flexibility of developing only a single application suite at a time.
        If used correctly, CGI::Application can be used as a very good Controller for an MVC setup -- have it simply do the work of validating and sanitizing input, passing it to the Model, and piping the Model's return values to the View (a templating system).

        What I like most about it is that, at it's core, it's a very slim piece of code that simply stays the heck out of my way as I build my applications -- no extraneous doodads or geegaws are loaded unless I specifically do so myself.

        Yes, it's another dependency, but it has very little overhead and benefits that outweigh the dependency a thousandfold.

Re: Model-View-Controller: Template Toolkit vs. XSLT
by iburrell (Chaplain) on Oct 14, 2004 at 17:18 UTC

    XSLT makes the most sense if your data is in XML to start with. Transforming relational database to XML and then to XHTML with XSLT adds an extra step. But, for example, an aggregator might use XSLT to transform RSS and Atom.

    XSL-FO is for printing. Programs like FOP render it into PDF.

      I've had some success using Template::Plugin::XML::LibXML for parsing simple XML files. This allows me to process XML using XPath, my favourite part of XSLT, without XSLT's syntax, which I find a little verbose and fiddly. Your tastes may vary, but my point is that XSLT isn't the only templating system that can process XML documents.

      It still helps if you learn XPath, which takes time, but provides a very convenient way of accessing data in tree structures.

Re: Model-View-Controller: Template Toolkit vs. XSLT
by CountZero (Bishop) on Oct 14, 2004 at 18:43 UTC
    Personally I use T::T to output XML from a database and then send this XML through XSLT (thanks to Template::Plugin::XSLT) to make the final HTML.

    T::T plays nice with Apache, mod_perl, DBI and MySQL.

    CountZero

    "If you have four groups working on a compiler, you'll get a 4-pass compiler." - Conway's Law

Re: Model-View-Controller: Template Toolkit vs. XSLT
by Corion (Patriarch) on Oct 14, 2004 at 16:52 UTC

    From my short encounters with templating systems, I offer you those three terse reviews:

    • Template Toolkit sucks. I don't know why other people like it, but they do.
    • XSLT sucks even more. It has all the features of Template Toolkit, but you have to write them in verbose XML, without being able to output non-XML.
    • I have no experience with XSL-FO, therefore it must suck even more.

    If my reviews are too terse for your taste, or you crave other opinions, consider Super Search, which has many discussions of templating systems on this site. Personally, I haven't found a single templating system that suits all my needs, so I switch between HTML::Template, Petal and Template::Toolkit.

      Just a nit:
      XSLT sucks even more. It has all the features ... without being able to output non-XML.
      It's easy (well, easy in XSLT standards {grin}) to output non-XML. Take, for instance, this stylesheet.

      -- Douglas Hunter

        Not if you want/need control over the whitespace. And if you want to output XML-like, but not XML-compliant structures, like, say, Apache config files, the whole thing becomes even uglier.

Re: Model-View-Controller: Template Toolkit vs. XSLT
by FoxtrotUniform (Prior) on Oct 15, 2004 at 02:02 UTC

    I played around with XSLT a little bit some years ago. I found it a painfully verbose language to program in: the extra markup associated with keeping XSLT "legal XML" made the program disappear into the language, so to speak: one twenty-character XML tag starting with "xslt:" looks much the same as another. What really irritated me was that so much of the markup was redundant; maybe purpose-built XSLT editors (or emacs or vim modes) would add that in automatically (someone's already suggested using TT to generate XML).

    That's a pity, because XSLT looks like it might be a useful little side-effect-free language. For the moment, though, I'd say that if you desperately want your program to be data, for heaven's sake use Scheme. If I was being paid to produce XSLT code, I'd write a Scheme source filter.

    --
    Yours in pedantry,
    F o x t r o t U n i f o r m

Re: Model-View-Controller: Template Toolkit vs. XSLT
by simon.proctor (Vicar) on Oct 15, 2004 at 08:34 UTC
    Two things I think people always forget when considering XSLT are that to do XSLT well you need to know XPath and that sometimes you need to extend XSLT with your own custom functions to make life easier.

    As to your novice programmers. Well if they already know Perl then picking up TT should be a snap. If they are manipulating XML then they will have to learn XML/XSLT/XPath anyway. However, I find XSLT very frustrating as outputting plain text or maintaining correct formatting in a document can be hard. Add in complex XPath and then I find myself reaching for TT or for HTML::Template.

    At work, I tend to use XSLT purely in XSL-FO and create the underlying XML via TT. I rarely use XSLT out of the box unless my underlying data is in XML to begin with. So you know, XSL-FO can be used to create RTF and PDF documents (to name a few).

    Of course, language neutrality is a boon for XML but there is nothing stopping you exposing whatever service you provide as a webservice or adding an additional output switch (for the command line as an example) for added interoperability.

    My own personal take is that it depends. It depends on whether you are going to be processing XML most of the time, you have data in XML format or you need to interoperate between systems/applications. If your programs aren't going to do this then there probably isn't a need for XML at that time.

    If you do decide to use XML/XSLT then you will need a good and fast library. For that I would recommend the LibXML and LibXSLT libraries from the Gnome project.

    HTH
Re: Model-View-Controller: Template Toolkit vs. XSLT
by perrin (Chancellor) on Oct 15, 2004 at 00:03 UTC
    I've had excellent results getting novice programmers (even those who just know HTML and some JavaScript) to write and maintain TT templates. I haven't tried it with XSLT, so I can't comment on that. I doubt you will ever need to switch implementation languages without wanting to modify your templates, so I don't put much value on the language neutral claim, but maybe someone has an anecdote about sharing templates between Perl and Java or something.
Re: Model-View-Controller: Template Toolkit vs. XSLT
by Matts (Deacon) on Oct 16, 2004 at 21:16 UTC
    You'll hear a lot of bad stuff about XSLT from Perl programmers. There are two reasons for this:

    a) They are perl programmers not XSLT "programmers".
    b) Perl geeks don't like XML.

    Believe some of the hype, not all of it. And believe some of the bad stuff, not all of it.

    I've created some very large projects using XSLT and AxKit, and while XSLT isn't the easiest thing in the world, it does have some nice features, such as being declarative (something almost no other perl templating solution achieves well) and being nicely standardised.

    There are some comments about non-portability of stylesheets between processors, but assuming you don't use "extensions" then this does not bear out in the real world - stylesheets port very well between platforms.

    In closing, my personal opinion is that TT is nice, but is much more of a programming language than XSLT is (despite XSLT offering functions and variables). XSLT is more likely to be understood by future "Design Geeks".

      templating systems will never be better than XSLT's for a couple of reasons

      it all has to do with language, encoding and xslt scripting /xpath

      one of my previous jobs was to make a xml engine for a cell phone game company so the game data could be passed as xml into the engine and translated for the various wap browsers out there.

      not only were there xslt's for the phone layout but for the different browser inconsistencies {you think web browsers are bad lol riiight} as well as for different language support {i remember kanji giving us a bit of trouble in this department, but just changing the laguage in the xml header fixed this iirc}

      by using xslt includes and imports we were able to eleviate a lot of the programming

      sure i love html::template , but it has limitations, and if i needed to provide an industrial strength application i would go xslt's
        templating systems will never be better than XSLT

        Never? You can't think of any situation where XSLT isn't the right tool for the job?

        it all has to do with language, encoding and xslt scripting /xpath

        I don't know exactly what you mean here, but Template::Plugin::XML::LibXML and Template::Plugin::XSLT have been mentioned earlier in this discussion, demonstrating that XPath works in non-XSLT environments. Which language and encoding issues does XSLT deal with better than all other templating systems? The latest version of Template Toolkit (2.14) offers improved Unicode support.

        I think the point you make with mobile phones is that XSLT can run on the client side, whereas other templating tools can't. I agree this can help in certain situations, but often I prefer to keep the client side as simple as possible, doing complex work on the server environment. As you mention, client side environments differ considerably in their treatment of the same information.

Re: Model-View-Controller: Template Toolkit vs. XSLT
by borisz (Canon) on Oct 15, 2004 at 11:05 UTC
    For a large application I go for pagekit.org it is a MVCC framework and has support for both, XML/XSLT and a RDBMS. The output templates are generated with HTML::Template or for newer version with Template::Toolkit at your option. XML/XSLT is processed with XML::LibXML and XML::LibXSLT.
    Personaly I use XML only to move static parts of my HTML output out of my templates.
    Boris

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlmeditation [id://399245]
Approved by Old_Gray_Bear
Front-paged by !1
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (2)
As of 2024-04-18 23:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found