Slashdot Mirror


Web Development - The Line Between Code and Content?

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?"

13 of 156 comments (clear)

  1. Simple by neoform · · Score: 3, Insightful

    Seperated: If you want something modular and scalable (but slower)

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

    --
    MABASPLOOM!
  2. Depends by deblau · · Score: 5, Informative
    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.

    --
    This post expresses my opinion, not that of my employer. And yes, IAAL.
  3. Logic vs Presentation by illuminatedwax · · Score: 4, Insightful

    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.

    --
    Did you ever notice that *nix doesn't even cover Linux?
    1. Re:Logic vs Presentation by Just+Some+Guy · · Score: 4, Interesting
      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">
      <tr>
      <th>First name</th>
      <th>Last name</th>
      </tr>
      <tr>
      <td>Jim</td>
      <td>Johnson</td>
      </tr>
      </table>

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

      <table summary="some table">
      <tr>
      <th>First name</th>
      <th>Last name</th>
      </tr>
      <tr tal:repeat="row here/customerlist">
      <td tal:content="row/firstname">Jim</td>
      <td tal:content="row/lastname">Johnson</td>
      </tr>
      </ 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.

      --
      Dewey, what part of this looks like authorities should be involved?
  4. Yeah, I do that. by Anthony+Boyd · · Score: 4, Informative

    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. :)

  5. Depends on usage by jasonla · · Score: 5, Informative

    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.

  6. Separation good by legLess · · Score: 3, Insightful

    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?

    --
    This isn't as much "normalization" as it is "don't take so many drugs when you're designing tables."
  7. Depends. by Ant+P. · · Score: 3, Informative

    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.

  8. You gotta keep'm separated by Shawn+is+an+Asshole · · Score: 3, Informative
    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:

    template.tpl:


    <?xml version="1.0" encoding="utf-8"?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd ">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>{$title}</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    </head>
    <body>
    <table>
    {section name=mysec loop=$products}
    <tr style="background-color : {cycle values="#f6f6f6,#e6e6e6"};">
                    <td>{$producs[mysec].sku}</td>
                    <td>{$producs[mysec].description}</td>
                    <td>{$producs[mysec].price}</td>
    </tr>
    {/section}
    </table>
    </body>
    </html>


    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);
    $smarty->display("template.tpl");


    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.
    --
    "It ain't a war against drugs.it's a war against personal freedom" --Bill Hicks
  9. Struts - A Possible Cure-all? by WeAzElMaN · · Score: 4, Interesting

    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.

    -WeAz

  10. Re:Matter of Personal Preference? by jalefkowit · · Score: 4, Insightful

    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.

  11. Re:I never like this method by MaoTse · · Score: 3, Insightful

    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.

  12. Re:Matter of Personal Preference? by anomalous+cohort · · Score: 4, Informative
    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.