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

9 of 156 comments (clear)

  1. 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.
  2. Try using XML and XSL by rkwright · · Score: 2, Informative

    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 always coming from the config files and web service calls always stays the same and doesn't care about the markup. The downside here is that this method requires that any database calls or business logic is returning XML. It works great for us, since we're moving all of our logic into a web service layer, and the services always return XML. This might require more architectural work than is necessary in your case, but if the web app is big enough or complicated enough, this method provides some great decoupling.

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

  4. 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.

  5. Model View Controller by lorcha · · Score: 2, Informative

    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.

    --
    "Avoid employing unlucky people - throw half of the pile of CVs in the bin without reading them." -- David Brent
  6. 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.

  7. 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
  8. 3 layers by nuttzy · · Score: 2, Informative

    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 in the first place.

    However the last layer, the CSS, is the most over looked. CSS has wide browser adoption now and is extremely powerful. There are numerous performance benefits for using minimal HTML and pushing things to CSS, mostly centering around CSS getting cached locally. But CSS also provides a tremendous amount of flexiblity for layout. You can drastically change the layout simply by changing the CSS.

    More over, when built this way, you can let a much lower cost CSS specialist (pixel pusher) worry about how much padding there and what color widget there, and let us Web App Developers stick to the meat of the project. It's a great way to split the task up in a team environment.

    I cannot over emphasize checking out CSS Zen Garden.
  9. 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.