Slashdot is powered by your submissions, so send in your scoop


Forgot your password?

Web Development - The Line Between Code and Content? 156

markmcb asks: "I help design a LAMP web site and I'm constantly plagued by trying to decide on what level should I separate functional code and markup. Depending on what you read, some say embedding HTML in your PHP scripts [or Perl, or Java, or Ruby, or Python, etc] is bad while others say it's no big deal. However, seldom are any practical applications of such code cited. How is your site built? Do you mix HTML with your code? If not, how do you overcome the simple and easy method of doing so? Lastly, what performance gains/losses have you noticed by doing so?"
This discussion has been archived. No new comments can be posted.

Web Development - The Line Between Code and Content?

Comments Filter:
  • I taught myself to script perl a few years ago, and no one told me one way or the other. So I decided to embed the html a bit in the code, and I really can't think of a good reason why it would be bad to mix the html, unless its for the sake of the clarity of the code.

    I had to implement an intranet site using zope/plone which seemed to prefer a separation, but I saw no reason for it, except the obvious use of templates, and just went ahead business as usual. So i think this is just a matter of preference.
    • Wait until your project grows to a point where you're not the only person working on it, and then come back and tell us if you still feel this way.

      Keeping markup out of your code means that you can, for example, bring in a graphic designer to change the look and feel your site/app without requiring that they know Perl (or PHP, or whatever) -- very few designers know, or care, about programming. And it means that you can bring in other programmers to fix bugs/add features without worrying that their changes will muck up the UI.

      • by anomalous cohort ( 704239 ) on Friday May 19, 2006 @10:21AM (#15365276) Homepage Journal
        Keeping markup out of your code means that you can, for example, bring in a graphic designer to change the look and feel your site/app without requiring that they know Perl

        In my humble opinion, it should be the objective of the web developer to develop a web application where the markup is so well designed that the graphic designer need only modify the CSS file in order to make whatever changes he or she requires of the web site's look and feel. Given a modern browser, you can get 80% there without trying real hard.

        I originally learned about the Zen Garden [] from another /. post. This is well worth studying to learn about good markup design from the standpoint of decoupling GUI from markup generation.

        The posters in this topic don't differentiate between content and markup. I am assuming that they are really interested in discussing the pros and cons of embedding markup in the code.

      • I totally agree. I try to make sure I sepperate my page template, css, images, and javascript all very clearly and break my code into one file for code that generates data (database, calculations, etc), and another file for code that converts the data into output. Where possible I break down code into services so that the lines between different functionality are clearly defined and all components are reusable.

        Javascript behaviors is a current favorite of mine if you have to deal with Javascript on your pag
  • I generally find it's best to remove all code from html as then it becomes portable to other projects easily...i'm sure this doesn't satisfy all your questions but i like to seperate functions from display, same with UI programming.
  • Depends. (Score:2, Interesting)

    by niteice ( 793961 )
    I personally find it easier to integrate (X)HTML with my PHP. When I've needed to store them seperately, though, I've seen no performance differences and I highly doubt that there would be anything significant. PHP is fast.

    Then again, I've never used Perl, Python, or Ruby for web development. Perhaps they're different.
    • I've thought about doing the integration part, but it just looks ugly and feels wrong to me for some reason.

      Instead, what I've done is create functions for most of the html commands I use so each .php file is 100% php from top to bottom. Using a php accelerator can help cache the entire script for faster operation.

      For example, using some functions I've put together, A page might look something like this:
      table(); tr();
      td(); iprint("Here's some text"); _td();
      _tr(); _table();

      Further, I have another funct
  • I use templates containing the HTML nowadays unless the HTML is very simple. There's a very nice Perl module, Text::Template, for using templates - you can embed Perl fragments in them too if you wish.

    I imagine that PHP and Ruby have similar things.
    • same here, use smarty & php. makes it very easy to dig through code, and even easier to change the look of pages.

      css driven templates are definately the way to go.
    • I second this! Templating systems abound, and are actually easier to use than embedding markup in code (or worse, code inside markup, as is possible with PHP[0]).

      In fact, looking at Perl's HTML::Template [] module, one can see how easily and quickly anyone with HTML knowledge can make a template.

      It's not just limited to HTML, either. The Template Toolkit [] is a very easy-to learn templating system that works for any kind of text-based templates. I've even seen it used to populate ODF documents...

      Basically, the
  • Simple (Score:4, Insightful)

    by neoform ( 551705 ) <> on Thursday May 18, 2006 @09:11PM (#15362359) Homepage
    Seperated: If you want something modular and scalable (but slower)

    Embedded: If you want something faster and easy to write (but not as scalable)
    • Embedded: If you want something faster and easy to write (but not as scalable)

      How is it easier to write if its embedded? When I think of embedded, I think of all the html and page content embedded in a servlet, aggregated in a var using String.Append or something similar, and then written to the output stream. It's a lot more difficult to maintain the HTML code in that form than it is if you keep the non-dynamic HTML in file.html and only embed the dynamic stuff in your server-side code. Although it d
  • Depends (Score:5, Informative)

    by deblau ( 68023 ) <> on Thursday May 18, 2006 @09:24PM (#15362415) Journal
    At my last job, we had 5 tiers:

    1. Resources (network, disk, database, etc)
    2. "Drivers" providing uniform data access to the resources
    3. Business logic
    4. Application logic
    5. Client logic

    Business logic would use the driver API, making data requests that were resource-neutral. In other words, the business logic didn't care where the data came from, only that it got what it asked for. Different business functions were isolated, and each presented its own API to the applications. The APIs themselves conformed to a specification. That way, apps written by different developers could perform the same business functions without recoding everything. The applications made requests of the business logic according to the spec, then presented the results to the clients for formatting (web, RSS, PDF, whatever). Uniform data structures were used throughout.

    You may not need that level of sophistication, but it sure as heck helped us prototype, isolate employee functions and skills, etc etc. It allowed us to run multiple OSes (Windows, Linux, Solaris) and multiple languages (.NET, VB, and Java) together seamlessly. It also helped when doing architecture, since it forced us to think about what a particular piece of code was really doing. Under our scheme, PHP would be layer 4, and HTML layer 5, so we would separate them. You could just as easily use PHP to generate XML, for example.

    • I am working on a project where I am using the same pattern (more or less).

      Here is how it is implemented:

      First the problem: The project is to import purchase orders, create a freight shipping request, price the request against an arbitrary number of trucking company rate tariffs, present the user with a list of rates, allow him to select the truck company, produce a PDF hardcopy bill of lading, and send the bill of lading via X12 EDI or SOAP to the truck company. Or alternately, the user can manually c
  • by rkwright ( 75860 )
    For the project we're working on, we are combining several bits of XML data and using an XSL template to display the HTML. This helps seperate the data from the markup. That way, your PHP or Perl would be responsible for getting the data (in our case, XML from web service calls and XML config files), handling user input, and running the XML/XSL transform. This solution works for us because we can dynamically call different XSL templates depending on the skin we want to display to the user, but the data a
  • by illuminatedwax ( 537131 ) <stdrange@alumni.uchic a g o . edu> on Thursday May 18, 2006 @09:25PM (#15362422) Journal
    People will always tell you to "separate logic from presentation" and that is good advice - to a certain extent. I don't think that this is correct all the time, however, because it is not a correct statement per se because the two cannot always be separated. However, they usually can and usually are, and web pages are a good example of this. But what does "separate" mean? Does it mean physically moving your presentation to another file, generating it, etc.? There are many different ways, all of which work best in certain situations.

    Here's what you should worry about instead:
    1) Is the program readable?
    2) Can you easily make changes in the program without having to change too many other parts of it?
    3) Are you having to rewrite the same code too much?

    Those are some pretty basic computer programming design concepts, and if you apply those, you'll find that the answer should be pretty clear. Just keep everything clean and life will be happier.
    • by Just Some Guy ( 3352 ) <> on Thursday May 18, 2006 @10:41PM (#15362751) Homepage Journal
      I don't think that this is correct all the time, however, because it is not a correct statement per se because the two cannot always be separated.

      In general, I disagree. Zope use a page template language that works like this:

      First, you write plain HTML:

      <table summary="some table">
      <th>First name</th>
      <th>Last name</th>

      Let your design guys work on it until it looks pretty. Then you embed template code into the HTML:

      <table summary="some table">
      <th>First name</th>
      <th>Last name</th>
      <tr tal:repeat="row here/customerlist">
      <td tal:content="row/firstname">Jim</td>
      <td tal:content="row/lastname">Johnson</td>
      </ table>

      Zope calls a method named "customerlist" in the same directory (for our purposes here) and gets a list of dictionaries (Perl: hash tables) as results. Then, it loops across that list. For each row, it writes out a tr tag (without the "tal:" stuff), replaces the string "Jim" inside the first td tag with the value of the "firstname" key from that row, does the same for the "lastname" key, and closes the tr. If your method returns one row, Zope writes one row. If it returns 1,000, Zope writes 1,000.

      But the beauty is that the marked up template is still valid HTML that can be edited in Dreamweaver or whatever it is your web design guys like. They can do whatever they want to it, as long as they leave the "tal:" stuff alone. Then you, the programmer, write the "customerlist" method that pulls from a database, fetches from an Active Directory server, parses out of an email - whatever you think is appropriate. You don't care how the web guys write the HTML, and they don't care how you write the code.

      The real magic, though, is that any page on the site can call your "customerlist" method and mangle the output as it sees fit. If someone decides they want to see lastname come first, they just write the HTML; you don't touch a line of your code. Similarly, if you replace your MS-SQL backend with PostgreSQL, your web team doesn't even need to know. They just use the results without caring where they came from.

      If you can't see why this is code reuse nirvana, you don't have a very good imagination. In theory, this works great. In practice, it's even better.

      • Right after that comment I said: "and web pages are a good example of this."

        The method that you pointed out is great. It is a huge win. It does a great job of applying the three concepts I mentioned, and also happens to separate logic from presentation. But I think that in computer programming in general, separating the two is not always the best idea. In some cases, the distinction is artificial and therefore any kind of separation is going to be forced. It's usually those cases where there is "too much" l
      • Project Leader: Right you coder, the HTML designer doesn't understand PHP so you got use a template language instead you never heard off.

        Coder: Oh okay, I can do that, so Designer guy, you can help with learning this template language?

        Designer: No, I never heard of it either and I am going to just delete any html I don't regonise just like I do with php tags.

        Coder: Fuck.

        And this ain't a joke. My introduction to templates went pretty much like this. In order to deal with a designer who kept removing PHP

        • Wow. No offense, but that's a totally weak attitude. The entire basis of your post seems to be that you can't be bothered to learn a new templating language. And you're a coder??

          We're using Zope/Plone in my organisation to replace our current intranet system. So a couple of months ago I went over to India to get some training on the system. Had I ever used, seen or even heard of tal templating before? Nope. Guess how long it took me to pick it up? Uhm... about one afternoon. Seriously. It's a fri

          • The entire basis of your post seems to be that you can't be bothered to learn a new templating language. And you're a coder??

            No, the designer has his head up his ass. He won't deal with php tags (read: leave them alone), and when the coder uses what he wants, he still deletes the tags. My solution is, of course, to use php (the only thing at least one of them knows), and sit the designer down for an attitude adjustment.

            I'm the designer, who according to your rather patronising post, couldn't possibly m

          •'re going to sit there and whinge like a schoolgirl about "having to learn a new language"? Chrissakes. Just spend 2 or 3 hours learning it...

            Learning a programming language is not the same thing as learning a template system's syntax. It's not even the same as learning the programming language's syntax. 30 years experience of programming has taught me that you should expect to spend at least 2 or 3 months working with a programming language before you can safely consider yourself to have a ba

        • The point is: PHP does not support content/logic separation ;-)

          Your designer wanted to delete the code because it was breaking his design tool. Fuck ...

          Zope Page Templates do not have this problem.
        • Gah, fuck that. You can learn the templating language easily, you already *are* a coder and understand concepts like loops and conditionals which usually are miracles to any designer I met.

          The designer doesn't *have* to learn the templating language, don't be so lazy. Just let the designer do his thing and add the templating stuff later. As a tradeoff, tell him that he'll be goatse-ized if he removes your code from the HTML when he makes modifications to the design. Problem solved.

          As for alternating row bac
        • And this ain't a joke. My introduction to templates went pretty much like this. In order to deal with a designer who kept removing PHP because of the design program she used I had to learn a new "language" wich didn't help since she still kept deleting it.

          The solution is really simple: don't let non-coders work on code. Especially idiots like the one above.

          My designer keeps all her stuff neatly in the CSS. If she needs to do something in html, she writes the html and gives it to me, so I make sure my

        • Yikes, that designer sounds like a nightmare to work with.

          I myself am a designer, and I often run into the opposite problem: developers inserting nasty old broken HTML into my carefully-laid-out templates. It's not that I can't work with their jsp and php files, it's not that I don't have the time to do whatever it is that needs doing. Usually, it's just that they're in a hurry and don't bother to ask me to change or add something. Then I see the final app running one day and wonder what the hell happened.

        • The method is very similar to what is done in Tapestry, except that what you add is an attribute called jwcid to the standard tags. So the designer-coder dialog is more like "just make sure to leave any jwcid attributes you see in any tags, or we'll send you goons to beat you up" and that's it. Shouldn't be a problem.

          Besides, in the GP example, the designer makes the HTML templates first, then the coder adds the weird Zope tags. Maybe a standard html editor wouldn't know what to do with a tal:whatever attr

        • Designer: No, I never heard of it either and I am going to just delete any html I don't regonise just like I do with php tags.

          Coder: Ok, when you do that, I'll just back out the change. I can't be bothered to go reinsert my tags every time you touch something. And I'll also be talking to your boss.

  • My preference is to use Mason, a perl... well, it's a development framework to some, but it works as a pure templating engine as well. It allows embedding of perl snippets (and blocks, but that's best to avoid) in content documents. I prefer that balance. Occasionally you need display logic that can only be accomplished in code, it's unavoidable. So, my breakdown is: prepare data-structures the display will use, as shallowly as is reasonable for the display code, and then pass that along. Put a small chunk
    • I used to use Mason and it is a pretty good framework. But nowadays I've switched to Catalyst [], a framework and set of libraries that make MVC pretty easy. It has the added bonus that it supports a number of web engines (e.g mod_perl 1 and 2, CGI, FastCGI, etc) while I've given up on getting my old Mason sites working with Apache 2. I like the use of TT2 [] as a template engine. It has a simple but powerful mini-language that helps enforce MVC seperation by not being a full-blown programming language. I think

  • I worked for this web shop which chose to seperate HTML from the code so they could hire cheap designers to draw up the HTML to make it look nice. Ended up no matter how simple we made the templates, and how much hand holding we had to do to show them how to do it, they *always* fucked it up somehow. They ended up hiring more experienced designers, paid a higher hourly rate but saved in the long term.

    I think it's horses for courses, some quick projects can benefit from mixed source. Some 'enterprise' level
  • Yeah, I do that. (Score:5, Informative)

    by Anthony Boyd ( 242971 ) on Thursday May 18, 2006 @09:27PM (#15362437) Homepage

    For me, I try to look at it from a practical perspective. I don't separate code & content because of some idealogical reason (well, OK, I do... but I use the following thinking to help me determine how to implement it). Instead, I separate code & content because I know that inevitably, some non-geek is going to need to change the look & feel. And I want to expose the least amount of code possible, so that they can do the least amount of damage.

    Therefore, here is how that plays out. First, I create everything procedurally, one huge page, HTML & PHP & CSS & JavaScript all mixed in together. Then, once I am no longer iterating through revisions frequently, I start to pull out the non-HTML bits. The CSS & JavaScipt are usually the first to go, with HTML tags to pull that code back in. The PHP gets two run-throughs. First, I move repetitive code into functions (I don't do a lot of OOP). Second, I break the PHP code into logical include files. So for example, I typically have a handful of libraries that set up the page. Those go into setup.php (database connections, handling the on/off issue with addslashes, and so on). Anything that is page-specific goes into another include file. What I'm left with is HTML with a few short PHP echo statements. For example, something like this might appear right after the BODY tag:

    <?php echo implode("\n", $messages); ?>

    ...just to output any status messages that my code generated. And then something like this might appear anywhere I had a PHP variable to drop into the page:

    Welcome back, <?php echo $username; ?>.

    ...and so on. The basic gist is that I offload the code into include files, and those files generate variables that contain whatever content is needed for display. The HTML page itself merely has some PHP include statements and a few PHP variables sprinkled throughout the page. By doing this, some random artsy-type or client who noodles with the HTML can usually still revise things without damage. They usually understand what they're seeing. And that's all I'm aiming for. I don't try to go any more hardcore than that -- no abstraction layers, etc. Oh, also, I try to avoid having more than 1 level of included files. In other words, my included PHP code does not use include() to pull in even more files. The nesting on some projects just drove me a bit nutty, so I try to only go 1 level deep. I rarely keep to it, but it's an ideal. :)

    • Therefore, here is how that plays out. First, I create everything procedurally, one huge page, HTML & PHP & CSS & JavaScript all mixed in together. Then, once I am no longer iterating through revisions frequently, I start to pull out the non-HTML bits.

      Is this really the easiest way to work with PHP? It sounds pretty awful. I go exactly the opposite direction: First, I get the exact content I need in XML, then I pass it through an XSL for that specific page type, which imports an XSL with gen

  • For larger web sites I separate the code into a Presentation Layer and a Business Layer.
    The Presentation Layer is simply PHP/JSP/whatever-code embedded in HTML. The Business Layer does not contain any markup at all, being mostly a wrapper around database calls but with an API that fits the application. Could be written in another language. For instance, for a web site that requires user accounts, User objects are owned by the Business Layer.

    Then let the Presentation Layer have a common library for common ma
  • by mongus ( 131392 )
    Life is SOOOO much easier when you separate your program logic from the view. For a long time I resisted thinking there wasn't much point. Now I use JSP for presentation only. All logic goes into Java objects that JSP can pull data from but I avoid doing any data writes from JSP. With the model and view separated I can easily change what gets displayed on a web page without worrying about breaking the program logic. As long as I don't remove access to any data that gets displayed I can update program logic
    • This is a Design Pattern called "Model-View-Controller" (MVC). It's fairly popular but not used as often as one would think, mainly die to ad-hoc software developers.

      In your case, perhaps separating the program logic into the Controller and the Model, which is probably what you're doing anyways. This means have Models that are modules that contain "real" program objects and Controller(s) which drive it all. Of course the view is presentation.

      The beauty of this, as you probably have seen, is that everythi
      • I've tried sticking to MVC in a desktop application I'm working on, and I've found it quite hard to integrate the three layers. Model is something you would have to have anyway, it's your data structures and business logic, so it's not an issue. View is usually going to consist of some UI widgets, so as long as you're not rolling your own controls, you won't be spending too much time there. But the Controller give me brainache, because it ends up responding in complex ways to multitudes of events, passing c
        • > But the Controller give me brainache, because it ends up responding in complex ways
          > to multitudes of events, passing control back and forth between the M and the V.

          We've had some good discussions here at work about that aspect of the MVC pattern. Reading and thinking about the problem has become pretty clear to me that a separate model (M) makes sense, but splitting the controller and view up does not. The issue being that output (V) and input (C) for a model (M) are tightly integrated with each ot
  • Break it up (Score:3, Interesting)

    by sehryan ( 412731 ) on Thursday May 18, 2006 @09:40PM (#15362485)
    My web pages break down as such...

    I build a content page using HTML and CSS. No tables unless it is to display data. Trying to make it as clean as possible.
    I then move any HTML that repeats throughout the site (usually header and footer) into includes.
    I then create the functions that will build my menus and populate the content. I put these into classes.
    Call the class in the header include. Call the functions where apporpriate, and viola! I have five documents: CSS file, header, footer, class/function file, and then all the other pieces that are left in the original HTML document. Usually I will end up with a six document that has all the javascript, if necessary.

    Technically, you could build the header and footer to be functions, and cut down to two documents, but I have found that to be a bit of overkill, as usually the stuff in these are not very dynamic.

    Now, there may be some HTML in my functions. After all, if the function is going to put out HTML, then it probably needs HTML in it. But I try not to build any function-type code into the HTML. The nice thing about this set up is the core HTML document needs virtually no maintenance, and can be used for every single content page, assuming you are passing which page you need to the appropriate function.
  • PHP is, for better or worse, easy for both coders and designers.

    That means if you are a coder you can create pages with PHP that output from script.

    But if you a designer you sprinkle PHP into your HTML where you need dynamic content.

    If you are truely trying to keep content and design seperate, then you need to create templates (that designers build) that PHP calls forth and populates with content.
  • Depends on usage (Score:5, Informative)

    by jasonla ( 211640 ) on Thursday May 18, 2006 @09:49PM (#15362524)
    The Smarty template engine [] offers a flexible and powerful tool for PHP developers.

    Where/when I choose to use templates versus embedded code depends on where in a web application the page is viewed. For example, I would use templates on the frontend of complicated sites that require pages to have different page displays, such as a newspaper. A regular news story may display differently from an editorial or op/ed piece. I also think the frontend of a website should be flexible because redesigns happen often.

    But I embed HTML on the backend because the admin control panels are more functional than asthetic. Also, the backend pages are more critical than frontend pages and I want admin pages to be self-contained (not reliant on templates that may or may not work or contain errors).

    If a user screws up a frontend template, the worst thing that can happen is that the page is unavailable until fixed. But if a user screws up a backend/admin page template, you're can't even access the backend to fix the problem.

  • Separation good (Score:4, Insightful)

    by legLess ( 127550 ) on Thursday May 18, 2006 @09:52PM (#15362531) Journal
    Separation is good. I can trot out the old "let coders code and designers design," but I often do both, and there are other benefits. You should look at model view controller []. You don't have to drink all the MVC kool-aid to get good ideas from it.

    Wonder why Slashdot looks like ass? I've spent a lot of time hacking Slash source and, until their recent refactors (and maybe even now) there was markup everywhere in the Perl. It made a redesign impossible without actually writing code, and possible introducing bugs.

    MVC says that the presentation layer should be separate from the rest of the application. If you think about it, that's the same idea as keeping presentation (e.g. CSS) separate from content (e.g. XHTML). That idea has clearly won out.

    Performance can be a factor for smaller systems, but if you cache your templates or have them precompiled (e.g. JSP) it helps. Also, programmer efficiency is almost always more important than code efficiency. Keeping the controller code and the view separate allows you to find and fix code bugs without wading through all sorts of presentation logic. Who cares about how a nested list is constructed in XHTML when you're trying to find out why your app is barfing?
    • For PHP, I have started using CodeIgniter [] which is a pretty light-weight MVC framework, and I highly recommend it. It's nice because it doesn't impose very many rules on you (unlike other frameworks) so you don't really have to modify your coding style much. Working with it feels like a framework should: just some stuff there to help you out, without getting in the way. Oh, and it has a great user manual [] (which is arguably the most important part when picking up a new framework).
  • by lorcha ( 464930 )
    I use the Model View Controller [] design pattern for UIs. I would suggest you do the same. The View is your pretty HTML stuff, the Model is the crap you want to display, and the Controller is where the code goes to fetch that content and save user input.
  • Depends. (Score:3, Informative)

    by Ant P. ( 974313 ) on Thursday May 18, 2006 @09:54PM (#15362543) Homepage

    The more proficient you are in web-based languages, the easier it is to separate stuff:

    At the bottom you just have a mashup of PHP and HTML using one file per page, with the odd file include for a header or whatever. I started out doing PHP by trying to fix something written this way; it's an easy way of learning what to avoid.

    One up from that is separating the layout into CSS, which is pretty obvious.

    From there you can move the logic behind the dynamic content into separate files, by using includes or classes or whatever. This is the most common way from what I've seen.

    If you want to take it to extremes, then you can get XSLT involved. Probably overkill for a lot of things since it involves juggling 4 languages at once, but I haven't tried it so I can't say whether it's worth it.

  • Get a good framework (Score:3, Interesting)

    by mangu ( 126918 ) on Thursday May 18, 2006 @09:55PM (#15362547)
    I use eGroupWare [] which was forked from phpGroupWare []. Both of these have a utility called "eTemplates" which does all the HTML for you. Try it, you'll like it, productivity is awesome, something like several pages of working, tested, debugged, HTML per day.
  • Well maybe not so simple, I guess I'll leave that up for you to decide. The answer though, whichever system is easier for you (and your team) to work with and maintain.

    On many small projects where I'm the only developer, doing both logic and layout, I had no problem keeping everything embedded. Now, for me personally html is a lot easier to look at in blocks, for example

    print EOF
    blah blah blah
    blah blah

    instead of
    print "blah blah blah\n";
    print "blah\n";
    print "blah blah\n";

    So I'd often do that.

  • by Shawn is an Asshole ( 845769 ) on Thursday May 18, 2006 @10:44PM (#15362767)
    Really. It saves you in the long run. It's difficult to make something something validate as, say, XHTML 1.0 Strict if html is scatterd all through the code. It will also be difficult to change the look later.

    If you're using PHP, there is an excellent library called Smarty []. It makes using templates very easy.

    With Smarty you can do something like this:


    <?xml version="1.0" encoding="utf-8"?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " ">
    <html xmlns="">
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    {section name=mysec loop=$products}
    <tr style="background-color : {cycle values="#f6f6f6,#e6e6e6"};">

    For your PHP it's simply:

    $products = array();
    $result = mysql_query("SELECT sku,description,price FROM products");
    while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
        array_push($products, array('sku' => $row["sku"], 'description' => $row["description"], 'price' => $row["price"]));

    $smarty = new Smarty;
    $smarty->template_dir = "templates";
    $smarty->compile_dir = "template_c";
    $smarty->assign("title", "The title of the page.");
    $smarty->assign("products", $products);

    With this I can easily change the layout later. No messing around with trying to find all the embedded html.

    Smarty also allows you to include other templates from within the template. There are tons of features in Smarty, it greatly improves my productivity.
  • Recently, I had to develop a web interface to a firewall (based off smoothwall). I decided to split the interface and implementation so I implemented the interface in C and used libtemplate for the html/js stuff.

    An example of this implementation is the web interface for my (crappy, mostly not working, hard to compile) cctv program at []

    In the source tarball the web interface is in the "devsec/web_interface" directory.

    The reason I did this was to allow the web developers to create
  • So many people these days have bought into the Smarty templates stuff. But what they have forgotten is that PHP is perfectly good as a template language. Why are they using a whole separate language to do a job that the very language that the 2nd language is written in can do just as well?

    I think it's that people are stuck on such total and complete separation of "logic" and "display" that they have this erroneous idea that the only way that can be done properly is to use two separate languages.

    But ask yo
    • The second example should be of course

      foreach($One as $LoopVar1)
      <tr><td><?php echo $LoopVar1 ?></td></tr>
    • If you really want to embed PHP into your HTML and want to cope those HTML monkeys happy it's worth knowing that the PHP interpreter understands this:

      <script language="php">
          your code here

      Unfortunately the language attribute is depreciated as of HTML 4.01 :( so your pages won't validate in their un-executed form, and PHP doesn't understand the type attribute.
  • by WeAzElMaN ( 667859 ) on Friday May 19, 2006 @12:52AM (#15363356)
    I'm part of a student-run group at my high school that is in charge of developing and maintaining our school's website, servers, and other infrastructure. This past fall, we began redoing our school's site which, up until that point, was a mish-mash of ASP and HTML. The code was ridiculous - in fact, if we ever get bored, we like to look at the old code for a good laugh. However, we put a lot of thought into different techs that could be used to redo the site. We considered PHP, ASP, Ruby-on-Rails, Python, and different Java solutions. In the end, we chose Apache Struts - it offers an incredible level of abstraction, but it works wonders for development.

    Struts works by seperating business logic, actions, and markup. If, in the future, we decide we want to ditch Struts, we can keep the BL and the markup and throw out the actions for whatever we choose to replace it with.

    More importantly, however, this allows us to keep code and markup seperate, allowing the backend team to tweak the code as they see fit and the layout team to likewise play with the JSPs.

    In my personal practices, I generally do my damndest to keep code and markup seperate. If I'm using PHP, for instance, I'll write a simple template class that I can use to feed data into HTML without fusing the two together. It keeps things organized and (most of the time) headache-free.

    I hope I've offered some useful insight - best of luck to you.

    • If you like Struts you should check out Stripes []. It performs a similar function but it is much easier to configure and maintain.
    • The problem with struts is that it builds on JSP's, and in JSP's it can be very tempting to use scriptlet code <%...%> to accomplish some task or another.

      Because JSP's don't force the separation of content and presentation, it becomes too tempting for non-craftsmen to slip here and there. And then slip a little more. And eventually, you take a look at that page which just doesn't seem to ever work quite right and it's a seething morass of c-tags, html-tags, and scriptlet code that you realize you're
      • Fortunately, we're scriptlet-free. We're pretty disciplined about keeping Java out of the presentation.
      • You know you can disable scriptlets in the container, right?
        • It's tough to close the barn door once the horses are out. Removing the scriptlet from all of the pages at this point would take a lot of time and provide no user-visible benefit, so we'll never get permission to do it. We just gradually work to eliminate scriptlets from the pages as we get a chance.

          Also, there always seem to be a few cases where two lines of scriptlet can save you huge heaps of difficulty trying to find another way to present some data (normally involving an API you have to work against
    • Why could you not save yourselves weeks of work and use a CMA (e.g. Drupal?)
      • That should of course read CMS []...

        I still wonder about the overkill- it's not as if you're doing a distributed e-commerce solution is it?
      • First, while I'm a huge Open-Source advocate myself, our advisor's a huge security nut and didn't want to use something like Drupal where Security flaws are found often. Additionally, we have some fairly intense webapps running on the site (File Manager, Course Documents, Course Calendar - all run off LDAP) - we didn't want to spend a lot of time mucking around with a CMS to get those features to work. In the end, I'm very happy with the way the site's turned out. I have no regrets using Struts whatsoeve
    • Did you check out Tapestry []? It's a completely different paradigm from JSP. I never liked Struts because it builds on top of JSP and I hate the JSP paradigm. Tapestry offers more elegant and maintainable design, cleanly separating HTML pages from the dynamic elements that go in the pages and the Java code controlling it all. Plus, everything is a component, and you don't have the limitations you get when using JSP. I would say it's even better than Java Server Faces.

      There is usually some resistance to learn

    • You should check out Spring's MVC as well. While you're at it, Spring might help with other areas of your code, like coupling and testability.
  • by jilles ( 20976 ) on Friday May 19, 2006 @01:07AM (#15363413) Homepage
    If your businesslogic breaks when you change the site layout then embedding HTML in your business logic clearly was a bad idea. Doing so gets you up and running soon but you pay the price later when doing maintenance.

    Putting some time and effort in separating logic and presentation is not a novelty. The MVC pattern dates from the seventies. The n-tier server architecture was invented shortly thereafter. These two are now well accepted architectures for separating logic and presentation.

    As for performance. Code that mixes everything together tends to be naive in multiple ways, including performance, security, extensibility, etc. Optimizing performance generally requires using caching, pooling and other types of strategies. These are hard to retrofit in monolithic single tier systems. Again there's no absolute truth here: you just may be the genius that gets it right in one go.

    So it all depends on the question are you the guy who's doing the maintenance and/or will you be there when the shit hits the fan when somebody else tries to do it for you. If so, you are probably better off doing a proper job. On the other hand, out of control IT projects are a great way to milk stupid customers. Many IT businesses have built their empire on that kind of incompetence and billions of dollars still change hands annually for software projects that are over time, over budget and ultimately disappointing.
  • With PHP it's really impractical to completely seperate out all of the HTML from the PHP. The situation can be helped a lot by planning out the development before hand. This planning really comes into play in two different situations:
    The first is that you should focus on breaking the code into modules. A lot of people overlook that newer versions of PHP have lot of OO features that can ease development- though these people tend to not be pro developers. If you plan the site out and break the code into
  • The only way around having HTML in your PHP source code that I can think of is to create a class for making pages, with methods such as adding an HTML element and writing the page. The main advantages are that you can write new HTTP headers whenever you want without worrying that HTML was already output because you can write the class to only output at the very last moment, and you can rewrite the class to conform to new versions of X/HTML as they come out if you're cunning enough when you write it. But rea
  • That is with no "bare html" inside. All the html is output via functions.

    so for instance to get the title tag I would have something like.

    function Title($title) {
    print("<head>{$title}</head>"); }
    Title("My title");

    Except that the function is part of a class wich does all the basic layout.

    Why? Well I find it easier to maintain. But is this any easier then use doing

    <head>My title</head>

    No not really. But what if the title is being gener

  • One thing to remember is *complete* seperation of data, presentation (style whatever) and code is never possible. Each are meaningless without some of the other. Seperation is a good practice wherever it's applied, but don't be fooled into becoming obsessed by it.
  • by soliptic ( 665417 ) on Friday May 19, 2006 @05:55AM (#15364204) Journal
    One thing I've noticed is that whenever web programming comes up on slashdot, a ton of people rush in to boast about how they only ever use full-blown MVC, presumably in an effort to look uber-professional and dissociate themselves from this 'dirty php hacker' stereotype.

    The thing is, sometimes dirty php hacks are fine.

    What are you coding? If I went to ebay, or amazon, or something like that, and they didn't have a serious n-tier architecture, and all their logic code was scattered randomly throughout their html source, that would be a proper WTF [].

    On the other hand, when I knock up some sort of ultra-basic blog for myself, or a cheesy feedback form for my band's website, or something like that, then using full-on OOP and MVC is an equally big WTF. In that situation, please stop about impressing other people on slashdot with your architecture model professionalism, and write something shamelessly quick and easy. You're going to be the only person updating it, so who cares?

    One further point on that subject... everyone praises a clean separation / MVC approach for being essential when you have multiple developers updating code. Well... true in a way... but there are qualifications to that. I remember doing some hacking on php blogging software Plog [] for a customer last year. That's completely OOP and MVC, using Smarty for templating, and the intellectual side of my brain was impressed with the cleanliness of the design patterns, but the practical side of my brain found it a pain in the arse. The client would say "you see this output of such-and-such a word on such-and-such a page, can we change it?" If it had been I'd go into the source for that page and it would be pretty much a single line of code...


    or something ludricously cryptic like that. So I'd have to trying and "trace" things from the by_categories.php through the templates into all the object classes... of course the OOP was so fully-blown that you'd reach some initial completely generic class whcih told you nothing, you needed something which inherited off something which inherited off something.... etc, etc. It was an absolute nightmare, for the simple reason that the documentation, like so many OSS projects, was extremely lacking, verging on non-existent. I went to their wiki and found a page with the perfect title, something like "which functions are handled in which classes", but it just said "coming soon".

    To their credit, when I asked on their forums I got a quick and friendly reply, but still, I think it illustrates my point. If you're going to put things into an elaborate architecture so that what-you-see-in-the-final-html-pages bears almost no direct relationship to organisation of the 'business logic' source files, then documentation is essential otherwise it's actually harder for multiple developers to hack than if you just stuff your html full of inline php.

  • After working on a project with various modules with various levels of bits of business logic and application logic in the content rendering areas, my coworker and I have decided on a new approach: the application will output XML, to be transformed with XSLT (server side or client side) to HTML, linking CSS. There are several advantages:

    1) You have a simply defined interface between the application and display. Bonus points for making DTDs.
    2) Most UI changes can be made in the CSS by somebody completely ign
    • 1) XSLTs are harder to write than JSP/PHP/Perl.

      Are they? I never really mastered Perl and never tried to master JSP and PHP, but if you know XML and functional programming, XSL is pretty trivial. It's a bit wordy because it's XML, but an editor with code completion can help.

      2) If you don't want your program to be slow, you have to generate your XML serially. This is harder than dumping data into variables and maps and referencing them from the content renderer.

      Not sure what you mean by this. I u

      • I mean building the XML in the first place. If you've got a 20,000 line document, DOM can get pretty slow.
        • I mean building the XML in the first place. If you've got a 20,000 line document, DOM can get pretty slow.

          Ah, yes. It's definitely worth it to avoid files that big. Transporting them from one server to the next is also kindof expensive.

          We use Slide [] for our repository and DASL+Lucene [] to query it (we clearly like apache a lot). In the past, due to limitations in Slide, DASL or Lucene, we tended to just grab everything that fit our search query and port-process in XSL, but our resident Slide expert point

  • 3 layers (Score:2, Informative)

    by nuttzy ( 877548 )

    A good web app has 3 layers: the code, the markup HTML (wireframe only), and the CSS. I strongly encourage you to check out CSS Zen Garden to gain insight to this powerful model.

    For a serious web app, mixing logic and presentation is disaster. It becomes a huge headache to change even a simple thing in your presentation. Other developers that need to edit your code can't jump right in. They have to sift through all your crap, completely killing any of the supposed time-savings of building it hastily i

  • I know I know... it's not LAMP, but the lessons I've learned using ASP.NET and using code separation are: do it. Having done a lot of inline coding, I think code separation really works better in the long run. I also looked at Ruby on Rails, and I have to say that I am impressed with level of separation that it fosters in your code as well. If you separate it, it's easier to read and maintain later on when you haven't seen it in 6-12 months. I am still maintaining legacy ASP code and it's way harder t
  • HTML should not ever be in your logic code, but you can have some logic in your PHP.

    For that to work you need a genuine logic layer. Using an MVC pattern can help a lot, but all you really need is to use something like the Smarty template engine ( Smarty will give you a simple templating language, then in your logic layer you assign the needed values for the template to use.

    In my current project I assign mostly arrays (like a DB resultset from ADODB's GetArray function), but there ar
  • I typically embed HTML within my Perl CGI code in order to just get things done initially. The primary focus is on functionality, not aesthetics or maintainability. Once things are functional, it depends on how complex the application is and who will be using/managing it. If it's just a quick and dirty admin script to do a few basic tasks, I wouldn't even worry about it. However, if it is something that is likely to continue to grow and be maintained by many users, I will typically move the HTML out of
  • 1) Avoid anything that will make you have reduntant copies of the same code, whether html or perl/php/java/whatever. That bring maintainablility through centralization of common things.

    2) Avoid code that is doesn't look semantically related to the actual work you are doing. That brings maintainability by avoiding over-abstraction.

    In this case, and in my interpretation, it means:

    1) use a good templating engine that lets you have a single place for the structural <html><head><etc>

  • The more the logic is separated from the code, the better.

    I am an artist/designer with a bit of programming skill. I used to use Gallery [] as the backend for my site []. Gallery 1.x spits out horrible, ugly table-based HTML. And this HTML is intimately entwined with its PHP code. I browbeat it into making reasonably clean HTML that I could style. It took a hell of a long time, because I had to dissect and understand a lot of its PHP code. I pretty much got a working knowledge of PHP doing this.

    Then updates happe
  • hmm that rimed sort of.. anyway, the model view controller approach works well. My HTML pages are mostly just that. I'm using Java so the HTML becomes struts tags, as well as custom tags. My feeling is that I want my JSP to be more HTML like than anything else. Where necessary I use JSP, but more often I use javascript instead. This means that someone who knows HTML and JavaScript can do a page up. They do not need to be super smart in JSP. The controller is all done in servlets. They process the fo
  • Easy.

    For me, it is clear anyway.

    Java is code, XSLT is the Layout and XML is the content.

    Furthermore, when you combine relationally, XML and XSLT code embedded into SQL databases, you have the ability to add security to your servers, that is not attainable otherwise.

    The reason, is that nothing is ever stored as a HTML file, or a file on the web server.

    Everything is a URL that translates into a SQL table to get XML or XSLT code to layout content.

    Thats right, to update your website you just talk to a bunch of

Don't tell me how hard you work. Tell me how much you get done. -- James J. Ling