Jump to content

Discussion - Do you separate your JS, HTML, and PHP?


roopurt18

Recommended Posts

I'm just curious how others separate the data getting dumped by their PHP scripts.

I've seen some PHP code with <?php and ?> all over the place, making it difficult to read.

A lot of times you'll see something like:
[code]
$Html = "some_html";
// Do some stuff
$Html .= "some_more_html" . $var . "combined_with_a_var";
$Html .= DoMore();
echo $Html;
[/code]
I use that myself for small segments of HTML.

However, for large blocks of HTML it becomes difficult to visualize the structure of the page when you combine a lot of PHP with a lot of HTML.  Lately I've been creating .html files that contain large chunks of HTML with slugs surrounded by curly braces.  Each chunk of HTML is surrounded by comments that I use in conjunction with a regexp to pull just that chunk from the file.

For example:
[code]
<!--HTML_CHUNK!-->
<div>
  <!-- 10 lines of html !-->
  {ROWS}
  <!-- more html !-->
  {ANOTHER_SLUG}
</div>
<!--HTML_CHUNK!-->

<!--ANOTHER_CHUNK!-->
<div>
  <!-- html for a row !-->
  {ROW_DATA}
</div>
<!--ANOTHER_CHUNK!-->
[/code]

Then in my PHP file I'll use something like:
[code]
$Html = PullFromFile(HTML_FILE, 'HTML_CHUNK');
$Row = PullFromFile(HTML_FILE, 'ANOTHER_CHUNK');
if(strlen($Html) && strlen($Row)){
  $Items = GetData();
  if(is_array($Items) && count($Items)){
    $Rows = '';
    foreach($Items as $Item){
      $Rows .= str_replace('{ROW_DATA}', FormatRow($Item), $Row);
    }
    $Html = str_replace('{ROWS}', $Rows, $Html);
  }
  echo $Html
}
[/code]

IMO, this is much easier to read and maintain.  I'm just curious if anyone else does something similar or what solutions you've come up with.
Link to comment
Share on other sites

When working on scripts
People say that putting HTM in php code makes the page load slower
But as you said its messy, and your talking mili seconds

I tend to just echo
Basic Page layout for me

[code]

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>My Page</title>
</head>

<body>
<?php
$myname = "Jamie";

echo "Hello world, how are you today.<br />\n"
."My name is ".$myname."<br />\n":

?>

</body>
</html>
[/code]

A couple of things to note

I dont put echo on each line, thats just nasty
I always use \n
It dont make a difference to the HTM page, but it does on the source code

And
Although when using double quotes to echo, I still escape for vars, this makes it easier to read

Remember you can build a script, then 6 months, or evan 6 years down the line, look at it again
So
Comments is a good idea. I am trying to start adding them in my scripts as well
Link to comment
Share on other sites

Gah, I just do what ever I see fit.  I normally just echo html if it isnt too long... Something i made the other day:

[code=php:0]
<?
session_start();
$START = microtime();
include("includes/static/word_art.php");
//error_reporting(0);
$inc = $_GET['act'];
if(empty($inc)) { $inc = "main"; }

// Provides: <body text='black'>
$inc = str_replace("/", "", $inc);
if (preg_match("/[a-z0-9]$/i", $inc))
{}
else {
   $inc = "not_found";
}
$pre = "includes";
if($inc == "error")
{
$inc = "error";
$pre = "errors";
}
else {
if(!file_exists("includes/$inc.php")) {
$inc = "static/not_found";
}
}
?>
<html>
<head>
<title>Lakeside Bistro</title>
</head>
<body background="/images/bg.gif">

<link rel="stylesheet" HREF="/style.css" type="text/css">
<table class="main_table">
 <tr>
   <td width="88%" class="header" colspan="3">
<? include("includes/static/header.php"); ?>
</td>
 </tr>
 <tr>
  <td width="*" class="nav_bar">
<? include("includes/static/nav_bar.php"); ?>
<? include("log.php"); ?>
</td>
   <td width="88%" class="content">
<div class="content">
<? include("{$pre}/$inc.php"); ?>
</div>
</td>
 </tr>
</table>
<?
$END = microtime() - $START;
if($END < 0) {
$END = 1;
}
?>
<div align="center"><font size="2"> This site took <?=round($END, 3);?> seconds to generate and is best viewed in <a href="http://www.microsoft.com/windows/ie/ie6/default.mspx" target="blank">Internet Explorer</a> at 1024x768 or higher screen resolution.</font></div>
</body>
</html>
[/code]
Link to comment
Share on other sites

i don't understand people who say "don't put your code in the HTML!!!" and then go into the HTML, put all these {$name} and {$whatever} syntax all over the place and say "now THIS is how it's done!!!". really? ok, so now instead of putting PHP in the code, you're putting a totally NEW language in the code which i have to learn, which has to be parse by PHP, replaced with the CORRECT code anyway and then output as normal? and then i need to install an accelerator to get it to work at 'normal' speeds? great!!!

i actually changed my approach a few months back on this one. previously, i used dreamweavers templates. i heard alot about 'templating engines', but when i read up on them, it was just disguising one lot of code with another set of syntax altogether, and you need accelerators etc to make up for all the parsing, etc, so basically i made my own that uses PHP instead of a whole new syntax.

i have found it a lot lot easier to do things this way compared to the old way mainly because it's encouraged a lot more structure into what i've done, and because everything is handled through one single template engine, i can make vast changes in one go. for example, i have automatic word filters, caching, GZIP, etc, all of which can be turned on and off by changing one var. there are plenty more benefits to what i do, but at the end of the day, its just my new preference - not for everybody.

the 'hardcore' will have you believing that the whole Model/View/Controller way is the "correct" and "only" way, but ultimately, the end results (the HTML) and the ease of upgrade/scalability are the only important things.

best article i've ever read on this whole seperation/templating, etc is here:
http://www.massassi.com/php/articles/template_engines/
Link to comment
Share on other sites

I usually keep most of the javascript in seperate files, sometimes in a folder for it self. When I code I always start the file with <?php and end it with ?>. It don't end and start again. In big applications I make a template system, else I just echo it. If many lines I use heredoc.
Link to comment
Share on other sites

Personally, I don't directly output HTML at all. I don't use a template engine either.

I treat (X)HTML for what it is: XML.

I use php5's DOM extension to create XHTML documents and output it after generation/manipulation of the tree is complete. I store the document-object in the GLOBALS array, so I can manipulate it ANYWHERE in my application.

This also allows for chunked caching, like with the better template enigines (with loadXML() to load chunks from cache). Additionally, it ALWAYS outputs 100% valid XHTML!

As for javascript, I never 'nest' any script, I place it in separate files. I think most will agree that is the 'clean' way to do it.
Link to comment
Share on other sites

[quote author=roopurt18 link=topic=107007.msg437730#msg437730 date=1158732716]
redbullmarky, what do you mean by accelerators?
[/quote]
things like ionCube, etc, that are designed to speed up PHP. Not sure how they work, but they work. but alot of these template engines need them to get things sped up to a 'normal' level, due to the extra parsing involved. me personally - i'd rather cut out the extra parsing from these template engines, and use the accelerator anyway to make my code 'fast', not 'normal'.

I'm not saying these templating engines are terrible, as they have alot of other uses, but they're far too heavyweight.
as for the speed: with a 'normal' PHP page, the PHP parser does just that - parses the page and we're ready to rock and roll. when introducing this extra level of syntax, eg Smarty, PHP has to go through the page replacing all the custom tags with 'proper' PHP code and then executing the proper PHP code. ok - so it gets cached, but for the sake of a little bit more simplicity for the designers, is it worth it?

my biggest gripe with templating engines is the 'justification' that goes with them. ultimately, they're responsible for building a page.

- "yes, but xyz engine does this!!!" - should that be the job of the template engine?

- "yes, but the files get cached!" - great, so along with all my code and the engines code, i get hundreds of additional pages in the cache?

- "its seperating the code from the HTML!!" - is it? is the new set of syntax really that much different to the old? people mistake this many times. replacing one set of code with another is not 'removal'. if anything, it's worse.

- "my designers cant break my code!" - if i had a designer that couldnt learn some simple control structures, etc in 30 minutes (foreach, if, echo, etc) then I'm afraid to say that I wouldnt want them working on my project anyway. what this generally amounts to is the coder telling the designer "Listen, I'm the daddy, you're my bitch, you can't be trusted to not break my code so you'll use this instead".

the fact that the new version of PHP (6) will be keeping short tags is good enough for me. <?=$hello_world; ?> vs. {hello_world} really isn't that hard.
Link to comment
Share on other sites

It's not the "putting php code in your html" that causes the fuss, it is the hard coupling of HTML in PHP logic that is all the fuss.

The people who will be the ones complaining will most likely be new to MVC developers. The idea behind MVC is to separate the View (the html) from the Model (the parts of php that do all the work.. database connecitons, arithmetic.. etc.)

The idea behind template engines, for those who seem to have the wrong end of the stick, is to allow the ability to change the template without having to refactor all of your code.

If you have everything mixed together, you are going to have a lot of work to do if a change is necessary.

In a separated application, the model provides nothing but the data to the view. This way the view handles _all_ of the layout, so the only thing to change when the layout changes is the view, and the model can be left alone.

OOP practice is what this has derived from, so you'll also often find that those who don't fully understand MVC, or don't fully appreciate why some use it, are those who don't fully understand OOP.
Link to comment
Share on other sites

I don't see any reason why you'd want to include control structures within a template, so I agree with redbullmarky on that point.  I think having to introduce extra syntax into HTML just so portions of it can be repeatable [b]is[/b] a bad idea.  Inventing a new language is rarely a good idea.

Separating most, if not all, of the major HTML from the data in a site makes it easier to design.  You can easily see the page structure just from the HTML, even if you're not the author or it was written 6 months ago.  I think it has the benefit of being more easily maintained.

Additionally, if the site you are writing is a general purpose site for, let's say restaraunts, it will improve your marketability.  It opens the door for multiple, completely different looking sites to run off the same set of source code.
Link to comment
Share on other sites

I agree with the 'creating new syntax', but tbh.. it's not exactly difficult to use Smarty's markup..

An example template that I use, based on Zend Framework's Zend_View..

[code]<!DOCTYPE blah blah>
<html>
  <head>
    <title><?php echo $this->escape($this->data['title'])); ?></title>
  </head>
  <body>
  <?php $this->include('header.tpl'); ?>
    <h1><?php echo $this->escape($this->data['heading'])); ?></h1>
    <form action="<?php $this->escape($this->data['form_action'])); ?>" method="post">
      <table>
      <?php foreach ($this->data['table_data'] as $row)
            {
                echo '<tr><td>' . $this->escape($row['col1'])
                   . '</td><td>' . $this->escape($row['col2']) . '</td></tr>';
            }
      ?>
      </table>
      <input type="text" size="15" name="mytextbox" />
      <input type="submit" value="Confirm" />
    </form>
    <?php $this->include('footer.tpl'); ?>
  </body>
</html>[/code]No processing or logic at all, all purely layout.
Link to comment
Share on other sites

[quote author=Jenk link=topic=107007.msg438563#msg438563 date=1158826786]
I agree with the 'creating new syntax', but tbh.. it's not exactly difficult to use Smarty's markup..
[/quote]
i definitely agree with that from what i have seen - however, PHP's markup for loops/echoing etc isnt that hard either, especially considering the fact that it avoids 'compilation' beforehand.

[quote author=Jenk link=topic=107007.msg438563#msg438563 date=1158826786]
An example template that I use, based on Zend Framework's Zend_View..
...
No processing or logic at all, all purely layout.
[/quote]
and the example you gave is more along the lines of what i'd personally do. no fresh syntax, etc. only thing i personally do differently is i never put HTML in PHP (eg, echo '<tr><td>') but thats a personal preference, and i tend to use simpler variables rather than objects, and i never personally use 'include' in templates. the class I wrote has an 'autoloading master template' with the doctype,stylesheet, JS etc, and the templates job is to slot in 'sub templates' which are the ones that differ for each page. works very well and very easy to use.

still - however it's done, there's no getting away from the fact that it's not THAT hard to understand either way, and you have the advantage of faster code.
Link to comment
Share on other sites

Just for clarity, the reason you'll see $this->foo in there is because the View object I use is what renders the template, to encapsulate all of the View properties and related functions (methods)

The $this->include() method is not the same as the language struct include - it will search the templates directory for that sub-template and include it.
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.