8

This has been bugging me today after checking the source out on a site. I use PHP output in my templates for dynamic content. The templates start out in html only, and are cleanly indented and formatted. The PHP content is then added in and indented to match the html formating.

<ul>
  <li>nav1</li>
  <li>nav2</li>
  <li>nav3</li>
</ul>

Becomes:

<ul>
  <?php foreach($navitems as $nav):?>
  <li><?=$nav?></li>
  <?php endforeach; ?>
</ul>

When output in html, the encapsulated PHP lines are dropped but the white space used to format them are left in and throws the view source formatting all out of whack. The site I mentioned is cleanly formatted on the view source output. Should I assume they are using some template engine? Also would there be any way to clean up the kind of templates I have? with out manually removing the whitespace and sacrificing readability on the dev side?

soulmerge
  • 73,842
  • 19
  • 118
  • 155
kevzettler
  • 4,783
  • 15
  • 58
  • 103
  • 7
    I'm really curious why you think it's important to have generated HTML that's "readable". Because to all the systems that actually matter (browsers, search engines, screen readers) how tidy the whitespace of the document is means absolutely nothing. – Peter Bailey Jun 04 '09 at 05:31
  • 13
    I have to agree that it is not important that it is readable. Nonetheless, I have noticed a correlation between cleanly generated HTML and clean codebases. It certainly helps the developer debug when the HTML outputted is clean. – Elijah Jun 04 '09 at 05:35
  • 2
    I'd also like to point out that clean, readable client-side code may help a potential employer's decision when looking at the source of your websites and applications. – Jimbo Feb 27 '13 at 13:11
  • 1
    @PeterBailey Tidy html would save time in debugging. – Ascendant Mar 27 '14 at 16:02

12 Answers12

13

That's something that's bugging me, too. The best you can do is using tidy to postprocess the text. Add this line to the start of your page (and be prepared for output buffering havoc when you encounter your first PHP error with output buffering on):

ob_start('ob_tidyhandler');
soulmerge
  • 73,842
  • 19
  • 118
  • 155
6

You can't really get clean output from inlining PHP. I would strongly suggest using some kind of templating engine such as Smarty. Aside from the clean output, template engines have the advantage of maintaining some separation between your code and your design, increasing the maintainability and readability of complex websites.

Marquis Wang
  • 10,878
  • 5
  • 30
  • 25
  • 5
    Smarty doesn't really help in this case. The control structures like `{if $foo}` and `` are really the same. For manipulating the html whe've got `tidy` as correctly pointed out by @soulmerge. – Exception e Nov 26 '09 at 18:20
4

The way I do it is:

    <ul>
<?php foreach($navitems as $nav):?>
      <li><?=$nav?></li>
<?php endforeach; ?>
    </ul>

Basically all my conditionals and loop blocks are flush left within the views. If they are nested, I indent inside the PHP start tag, like so:

    <ul>
<?php foreach($navitems as $nav):?>
<?php     if($nav!== null) : ?>
      <li><?=$nav?></li>
<?php     endif; ?>
<?php endforeach; ?>
    </ul>

This way, I see the presentation logic clearly when I skim the code, and it makes for clean HTML output as well. The output inside the blocks are exactly where I put them.

A warning though, PHP eats newlines after the closing tag ?>. This becomes a problem when you do something like outputting inside a <pre> block.

<pre>
<?php foreach($vars as $var ) ?>
    <?=$var?>
<?php endforeach; ?>
</pre>

This will output:

<pre> 
            0            1            2            3            4            5        </pre> 

This is kind of a hack, but adding a space after the <?=$var?> makes it clean.

Sorry for the excessive code blocks, but this has been bugging me for a long time as well. Hope it helps, after about 7 months.

user373100
  • 41
  • 1
4

i admit, i like clean, nicely indented html too. often it doesn't work out the way i want, because of the same reasons you're having. sometimes manual indentation and linebreaks are not preserverd, or it doesn't work because of subtemplates where you reset indentation.

and the machines really don't care. not about whitespace, not about comments, the only thing they might care about is minified stuff, so additional whitespace and comments are actually counter-productive. but it's so pretty *sigh*

sometimes, if firebugs not available, i just like it for debugging. because of that most of the time i have an option to activate html tidy manually for the current request. be careful: tidy automatically corrects certain errors (depending on the configuration options), so it may actually hide errors from you.

stefs
  • 18,341
  • 6
  • 40
  • 47
4

Does "pretty" HTML output matter? You'll be pasting the output HTML into an editor whenever you want to poke through it, and the editor will presumably have the option to format it correctly (or you need to switch editors!).

I find the suggestions to use an additional templating language (because that's exactly what PHP is) abhorrent. You'd slow down each and every page to correct the odd space or tab? If anything, I would go the other direction and lean towards running each page through a tool to remove the remaining whitespace.

Some Canuck
  • 846
  • 7
  • 13
  • Pretty looking HTML is almost a side-effect of a templating system.. It would still make perfect sense to use one alongside the whitespace-remover.. – dbr Jun 04 '09 at 12:58
3

I about fell over when I read "I'm really curious why you think it's important to have generated HTML that's "readable". Unfortunately, there were quite a few people on this page (and elsewhere) that think this way...that the browser reads it the same so why worry about the way the code looks.

First, keeping the "code" readable makes debugging (or working in it in general by you or a developer in the future) much easier in almost all cases.

Furthermore, AND MOST IMPORTANTLY, it's referred to as quality of workmanship. It's the difference between a Yugo and a Mercedes. Yes, they are both cars and they both will take you from point "A" to point "B". But, the difference is in the quality of the product with mostly what is not seen. There is nothing worse than jumping into a project and first having to clean up someone else's code just to be able to make sense of things, all because they figured that it still works the same and have no pride in what they do. Cleaner code will ALWAYS benefit you and anyone else that has to deal with it not to mention reflect a level of pride and expertise in what you do.

Joe Conlin
  • 5,976
  • 5
  • 25
  • 35
  • Yes. Pride in your work. It's not a "kpi" and it's not something for the external business world. But as a creator, how do I feel when I churn out spaghetti code? I feel soul dead. I feel like an animal lover who became a butcher. My code is my expression. It's my music and art. It has to sing. It keeps me awake at night and it allows me to sleep at night. It's my curse and my salvation. If I don't have a bond with my craft - my code, why even code? Thank you for expressing this Joe. – a20 Mar 25 '18 at 06:55
3

You few times I have tidied my output for debugging my generated HTML code I have used tabs and newlines... ie;

print "<table>\n";
print "\t<tr>\n";
print "\t\t<td>\n";
print "\t\t\tMy Content!\n";
print "\t\t</td>\n";
print "\t</tr>\n";
print "</table>\n";
Christian
  • 3,917
  • 2
  • 23
  • 40
  • 2
    that works, but it's one hell of a job. I don't know another method though... – Natrium Jun 04 '09 at 06:14
  • 2
    Oh I didn't say it was efficient. :) Just that its the way I have done it to debug multi-nested tables etc. – Christian Jun 04 '09 at 08:33
  • This trick does not work with `echo`... the `\n` and `\t` are rendered on the page as text. – Sparky Mar 23 '13 at 16:48
  • 1
    @Sparky When outputing `\n` and `\t` and other control characters you need to use double-quotes, not single-quotes. – esryl Mar 26 '13 at 16:37
2

If it's REAL important in your specific case, you could do this...

<ul><?php foreach($navitems as $nav):?>
  <li><?=$nav?></li><?php endforeach; ?>
</ul>

Although that is worse in my opinion, because your code is less readable, even though the HTML is as you desire.

Fenton
  • 241,084
  • 71
  • 387
  • 401
2

I don't care how clean the output is - it's the original source code that produced it that has to be easy to parse - for me as a developer.

If I was examining the output, I'll run it through tidy to clean it up, if it were required to take a good look at it - but validators don't care about extra spaces or tabs either.

In fact, I'm more likely to strip whitespace out of the output HTML than put any in - less bytes on the wire = faster downloads. not by much, but sometimes it would help in a high traffic scenario (though of course, gzipping the output helps more).

Alister Bulman
  • 34,482
  • 9
  • 71
  • 110
1

Viewing unformatted source is very annoying with multiple nested divs and many records each containing these divs..

I came across this firefox addon called Phoenix Editor. You can view your source in it's editor and then click "format" and it works like a charm!

Link Here

1

I Agree, A clean source is very important, Its well commented, well structured and maintence on those sources, scripts, or code is very quick and simple. You should look into fragmenting your main, using require (prior.php, header.php, title.php, content.php, post.php) in the corresponding places, then write a new function under prior.php that will parse and layout html tags using the explode method and a string splitter, have an integer for tab index, and whenever </ is in the functions string then integer-- whenever < and > but not /> and </ are in the string integer ++ and it all has to be placed properly.... , use a for loop to rebuild another string tabindex to tab the contents integer times.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
1

Try xtemplate http://www.phpxtemplate.org/HomePage its not as well documented as id like, but ive used it to great effect

you would have something like this

    <?php
$response = new xtemplate('template.htm');

foreach($navitems as $item)
{

$response->assign('stuff',$item);

$response->parse('main.thelist');

}
$response->parse('main');
$response.out('main');
?>
 And the html file would contain

    <! -- BEGIN: main -->
<html>
<head></head>
<body>
    <ul>
<! -- BEGIN: thelist -->
      <li>{stuff}</li>
<!-- END: thelist -->
</ul>
</body>
</html>