Jump to content
alxndre

Maintaining the format of the html tags.

Recommended Posts

I have a very stupid question.

I've been reading the source of the demo, and the source of some websites done with processwire, and i've noticed that all the html tags in their work are still properly formatted and indented even after using echo to write them. For example, a snippet of their navigation would look like:

<nav id="navigation" class="ten columns alpha">
    <ul class="nav group">
         <li><a href="#">Home</a></li>
         <li><a href="#">Accomodations</a>
              <ul>
                   <li><a href="#">Standard Room</a></li>
                   <li><a href="#">Deluxe Room</a></li>
              </ul>
         </li>
    </ul>
</nav>

properly indented. Whereas mine would look like

<nav id="navigation" class="ten columns alpha">
<ul class="nav group">
<li><a href="#">Home</a></li>
<li><a href="#l">Accomodations</a>
<ul>
<li><a href="#">Standard Room</a></li>
<li><a href="#">Deluxe Room</a></li>
</ul>
</li>
</ul>
</nav>

all flushed to the left, which is very hard to read.

How do you guys do it? Thanks.

Share this post


Link to post
Share on other sites

It's to do with keeping the indentations inside your echo lines as well:

Assume for this example that you're going to echo each part of an unordered list with a new echo per line:

echo "<ul>\n";
echo "  <li>Something here</li>\n";
echo "  <li>\n";
echo "    <ul>\n";
echo "	  <li>Nested</li>\n";
echo "    </ul>\n";
echo "  </li>\n";
echo "</ul>\n";

You can see that I've put the indentation in as part of the echo line so it will retain that spacing when echoed. The \n simply returns a newline so the next element in the source is on a new line.

I also could have written it like this:

echo "<ul>\n
 <li>Something here</li>\n
 <li>\n
   <ul>\n
  <li>Nested</li>\n
   </ul>\n
 </li>\n
</ul>\n";

Sorry - I forgot that there's a bug in the forum editor at present that messes up indentaions, but hopefully you get the idea.

Share this post


Link to post
Share on other sites

But lately I'm thinking more & more giving alignment in the "hard" source less priority. One trigger for that is that I rarely watch the hard souce ( only for stealing :-) ) & working with the generated source.

Sometimes developping & adding line-break & tabs etc in your source code make your code harder to read & the indentation of your source will stack up quickly. Indentation of individual code blocks is important but how the individual blocks look together I think is less important. Readability in my editor should be more important. ( proper indentation is time consuming )

How I handle indentation also depends on the project.

For large blocks of HTML in php I love to use "<<<EOF"

Share this post


Link to post
Share on other sites

It's to do with keeping the indentations inside your echo lines as well:

I figured as much. I just thought you guys we're using an easier technique because most sources I've seen around are perfectly indented.

Thanks! I'm new to processwire, barely 3weeks, and yet I've already used it for two websites. The only thing I love more than how powerful this CMS is, is how helpful and friendly the community is. I'll be sticking around for sure, and try to help whenever I can! :)

  • Like 5

Share this post


Link to post
Share on other sites

I generally try to use as little echo lines as possible. My code will be more like this

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

that way i don't have to worry about indention ...

  • Like 4

Share this post


Link to post
Share on other sites

I suppose in practice I probably do the same as Thomas actually ;)

Share this post


Link to post
Share on other sites

I used to care a lot about having nicely formatted HTML, primarily because it was much easier to debug. But now with inspector tools like those included with Chrome and Firefox, it's rare that I'm looking at the raw source anymore to debug things. The source formatting doesn't seem be to be worth the trouble given that the inspector tools are going to output it nicely formatted and structured regardless of where the linebreaks and tabs are in the HTML source. In fact, the extra "\t" and "\n" characters in the PHP generated markup often make the PHP side of it harder to read and maintain (you've probably seen me doing that too). So I guess I'm now of the opinion that this kind of formatting to the markup isn't nearly as useful as it used to be, and I'm trying to get away from doing it.

Share this post


Link to post
Share on other sites

I rarely indent my html anymore, mostly out of preference because I find it easier to read and find what I am looking for. And like Ryan said, the web inspector in chrome or safari make walking my html easy as pie.

As a general rule, I like to keep all my HTML as HTML and by that I mean that I never echo out HTML. Instead I work exactly like Thomas. Little bits of PHP in my HTML.

Share this post


Link to post
Share on other sites

Thanks guys! I started using thomas' suggestion when I read it, and it works great. It's not perfect but at least most of it is properly aligned. I guess I have to let it go and stop worrying about indentation.

Although sometimes, I really have to, because I teach part-time and I want the students to be able to read my examples easily. And yes, I'm introducing processwire to my students, instead of joomla and drupal which other schools usually use to teach cms. So there's hope that future web developers would be using processwire more and more!

Thanks again! :)

  • Like 7

Share this post


Link to post
Share on other sites

If you are still looking for a nice solution. Let PHP do the work for you. Try this: PHP Tidy (its included in PHP5)

Example:
 

<?php
$html = '<ul><li><h2>Chaos</h2><p>here comes the stuff</p><li><h2>Philosohie</h2><p>I love nice source code</p></li><li><h2>next Listpoint</h2><p>Help, got lost in indentation</p></ul>';

$tidy_options = array('indent' => 3,'output-xhtml' => true);
$tidy = new tidy();
$tidy->parseString($html, $tidy_options);
$tidy->cleanRepair();
$body = $tidy->body();
// Output
echo $tidy;

/* Output

<!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>
  </head>
  <body>
    <ul>
      <li>
        <h2>
          Chaos
        </h2>
        <p>
          here comes the stuff
        </p>
      </li>
      <li>
        <h2>
          Philosohie
        </h2>
        <p>
          I love nice source code
        </p>
      </li>
      <li>
        <h2>
          next Listpoint
        </h2>
        <p>
          Help, got lost in indentation
        </p>
      </li>
    </ul>
  </body>
</html>
*/

more Information:
http://id1.php.net/manual/en/book.tidy.php
http://tidy.sourceforge.net/docs/quickref.html#indent-attributes

 

  • Like 4

Share this post


Link to post
Share on other sites

Or you could go in the opposite direction and minify all your output, and never again worry about what it looks like to others because... it's all on 1 line and you are doing it in the name of saving bytes! I'm actually using this in my latest project and quite happy with the result. Though I've made some modifications to it (to account for removal of Javascript comments and leaving textarea fields alone), which I still need to submit as a PR to michamichamicha.

  • Like 4

Share this post


Link to post
Share on other sites

Agree with ryan here.

Having no space between tags has an other advantage. Take the following ul li example I created on jsbin.

Here you can see we don't have the annoying whitespace gap between li items.

Normally for static positioned elements the white-space or a multitude of whitespaces is converted to a little space between inline elements.

  • Like 1

Share this post


Link to post
Share on other sites

Or you could go in the opposite direction and minify all your output, and never again worry about what it looks like to others

It's good to have an option to switch easily. (debugging, teaching etc.)

Share this post


Link to post
Share on other sites
It's good to have an option to switch easily. (debugging, teaching etc.)

I've got my version of the Minify module set to minify only when $config->debug ==  false. This is one of the updates I was going to submit a PR for. 

  • Like 1

Share this post


Link to post
Share on other sites

@Ryan: not sure if you've included that in your version, but you might also want to avoid minifying content within pre tags.

Personally I'd also leave script tags alone. The minifying solution I used as basis for example code in my hooks blog post didn't originally account for that, which is why it blew my site apart under certain specific conditions. Could've avoided this by altering embedded scripts, but it felt safer to simply skip them.

If I really wanted to minify JS, I'd rather use a service built for that -- better results, fewer issues :)

  • Like 1

Share this post


Link to post
Share on other sites
@Ryan: not sure if you've included that in your version, but you might also want to avoid minifying content within pre tags.

Good idea, I'll add that. 

Personally I'd also leave script tags alone. The minifying solution I used as basis for example code in my hooks blog post didn't originally account for that, which is why it blew my site apart under certain specific conditions. Could've avoided this by altering embedded scripts, but it felt safer to simply skip them.

I agree. It could be problematic with some scripts. Perhaps it should be a configurable option as to whether scripts should be minified or not. Or better yet, an extra attribute on the script tag: <script minify> so it knows it's fair game.

If I really wanted to minify JS, I'd rather use a service built for that -- better results, fewer issues 

True, but we're talking about inline scripts in this case. I'm too lazy to go and re-minify inline scripts every time I need to change something. :) 

  • Like 1

Share this post


Link to post
Share on other sites

Hi there,

I'm currently using the direct output method for my templates where the prependTemplateFile is my header & navigation and my appendTemplateFile is the footer of the website. In addition to that, I include other commonly shared files into the templates via "include_once('file.php')".

The navigation file that gets appended to every template:

<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
        <div class="container">
            <!-- Brand and toggle get grouped for better mobile display -->
            <div class="navbar-header sc-content">
            	<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button>

            	<a class="navbar-brand" href="<?php echo $pages->get(1)->url; ?>"><img src="<?php echo $config->urls->templates?>/images/titlebar.png"></a> <!-- link zu Startseite (id=1) mit bild f�r navigationsleiste -->
            </div>
            <!-- Collect the nav links, forms, and other content for toggling -->
            <div class="collapse navbar-collapse sc-content" id="bs-example-navbar-collapse-1">
            	<ul class="nav navbar-nav navbar-right">

                 <!-- In Mobile ansicht (xs) anzeigen wegen Anordnung. -->
                <li class="visible-xs">
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown"><img src="<?php echo $user->language->image->first->url; ?>" alt="<?php echo $user->language->title; ?>"> <b class="caret"></b></a>
                        <ul class="dropdown-menu">
                            <?php
                                // remember what language is set to
                                $savedLanguage = $user->language;
                                foreach($languages as $language) { //alle sprachen durchgehen
                                  // if user is already viewing the page in this language, skip it
                                  if($language->id == $savedLanguage->id) continue;
                                  // if this page isn't viewable (active) for the language, skip it
                                  if(!$page->viewable($language)) continue;
                                  // set the user's language, so that the $page->url and any other
                                  // fields we access from it will be reflective of the $language
                                  $user->language = $language;
                                  // output a link to this page in the other language
                                  $path = $language->image->first->url;
                                  echo "<li><a href='$page->url' alt='$language->title'><img src='$path' alt='Flagge von Sprache'> $language->title</a></li>";
                                }
                                // restore the original language setting
                                $user->language = $savedLanguage;
                            ?>
                        </ul>
                    </li>
                    <!-- Telefon mit link zu kontakt in mobile ansicht verborgen -->
            		<li class="hidden-xs"> <a href="<?php echo $pages->get(1022)->url; ?>">Tel: xxxxxxxx</a> </li>
                    <!-- Telefon mit link um anzurufen in mobile ansicht sichtbar -->
                    <li class="visible-xs"> <a href="tel:+41-44-233-30-30">Tel: xxxxxxxx</a> </li>
					<li class="visible-xs"> 
                      <a href="<?php echo $pages->get(1)->url; ?>">
						<span class='glyphicon <?php echo $pages->get(1)->glyphicon; ?>' aria-hidden='true'></span>
						<?php echo $pages->get(1)->title; ?>
					  </a>
                  	</li>
					<!-- Ausgabe aller Seiten f�r Mobileansicht (visible-xs) -->
					<?php
                        foreach ($pages->get(1)->children as $navitem) {
                            echo "<li class='visible-xs'>
                                        <a href='$navitem->url'>
                                            <span class='glyphicon $navitem->glyphicon' aria-hidden='true'></span>
                                            $navitem->title
                                        </a>
                                </li>";
                        }
                    ?>
            	</ul> <!-- navbar-nav -->
            </div>
            <!-- /.navbar-collapse -->
        </div>
        <!-- /.container -->
    </nav>

The template file and the appended footer file are very similar in terms of format and coding style.

Now the final output/source of the website is not formatted at all, not even all the linebreaks.
I tried to include the formats in the echos and use as much HTML as possible (like thomas descirbed above) but I feel like the prepend/append and included files mess up/ignore the format:

<!DOCTYPE html><html lang="de"><head><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1"><meta http-equiv="content-type" content="text/html;charset=ISO-8859-1" /><meta http-equiv="content-language" content="de" /><link rel="stylesheet" href="/site/assets/aiom/css_fcf3e08b16c1fb16f6f309285c212e13.css"><link rel="shortcut icon" type="image/png" href="/site/assets/files/1062/favicon.png"/><!--[if lt IE 9]><script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script><script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script><![endif]-->	[..]
</head><body><nav class="navbar navbar-inverse navbar-fixed-top" role="navigation"><div class="container"><div class="navbar-header sc-content"><button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"><span class="sr-only">Toggle navigation</span><span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span></button><a class="navbar-brand" href="/"><img src="/site/templates//images/titlebar.png"></a></div><div class="collapse navbar-collapse sc-content" id="bs-example-navbar-collapse-1"><ul class="nav navbar-nav navbar-right"><li class="visible-xs"><a href="#" class="dropdown-toggle" data-toggle="dropdown"><img src="/site/assets/files/1017/germany-v1.png" alt="Deutsch"><b class="caret"></b></a><ul class="dropdown-menu"><li><a href='/en/' alt='English'><img src='/site/assets/files/1019/english-v1.png' alt='Flagge von Sprache'> English</a></li><li><a href='/fr/' alt='Francais'><img src='/site/assets/files/1020/french-v1.png' alt='Flagge von Sprache'> Francais</a></li></ul></li><li class="hidden-xs"><a href="/kontakt/">Tel: xxxxxxx</a></li><li class="visible-xs"><a href="tel:xxxx">Tel: xxxx</a></li><li class="visible-xs"><a href="/"><span class='glyphicon glyphicon-home' aria-hidden='true'></span>
							xxxx					</a></li><li class='visible-xs'><a href='/standort/'><span class='glyphicon glyphicon-map-marker' aria-hidden='true'></span>
                                            Standort - so finden Sie uns
                                        </a></li><li class='visible-xs'><a href='/kontakt/'><span class='glyphicon glyphicon-earphone' aria-hidden='true'></span>
                                            Kontaktinformation
                                        </a></li><li class='visible-xs'><a href='/angebot/'><span class='glyphicon glyphicon-apple' aria-hidden='true'></span>
                                            Unser Angebot
                                        </a></li><li class='visible-xs'><a href='/konzept/'><span class='glyphicon glyphicon-file' aria-hidden='true'></span>
                                            Unser Konzept
                                        </a></li><li class='visible-xs'><a href='/team/'><span class='glyphicon glyphicon-user' aria-hidden='true'></span>
                                            Das xxxx-Team
                                        </a></li><li class='visible-xs'><a href='/links/'><span class='glyphicon glyphicon-globe' aria-hidden='true'></span>
                                            Links
                                        </a></li><li class="hidden-xs"><a href="#" class="dropdown-toggle" data-toggle="dropdown"><img src="/site/assets/files/1017/germany-v1.png" alt="Deutsch"><b class="caret"></b></a><ul class="dropdown-menu"><li><a href='/en/' alt='English'><img src='/site/assets/files/1019/english-v1.png' alt='Flagge von Sprache'> English</a></li><li><a href='/fr/' alt='Francais'><img src='/site/assets/files/1020/french-v1.png' alt='Flagge von Sprache'> Francais</a></li></ul></li></ul></div></div></nav>

Is there a way to keep the format of the files included and or prepended/appended?
or what am I doing wrong?

Share this post


Link to post
Share on other sites
17 hours ago, joeck said:

what am I doing wrong?

It's hard to tell without some sample code. Can you provide us with a shortened example of how you are constructing your output?

Share this post


Link to post
Share on other sites
1 hour ago, szabesz said:

It's hard to tell without some sample code. Can you provide us with a shortened example of how you are constructing you output?

very fair point, just updated my post

  • Like 1

Share this post


Link to post
Share on other sites

Thanks for the code sample, I cannot see anything suspicious there, it is very similar to how I do things and in my case the output is formatted in the browser just as expected. You might want to check the type of line breaks you use, I always use Unix LF so I have no experience with Windows CRLF for example.

17 hours ago, joeck said:

my templates where the prependTemplateFile is my header & navigation and my appendTemplateFile is the footer of the website.

That said, your code might be "messed up" because prependTemplateFile and appendTemplateFile, so you might want to try constructing your page similar to this:

https://www.pwtuts.com/processwire-tutorials/alternate-template-strategy-using-a-single-output-file/

<body class="<?php echo $page->template->name; ?>">
<?php
include($config->paths->templates . "/includes/header" . ".php");
include($config->paths->templates . "/views/{$page->template->name}" . ".php");
include($config->paths->templates . "/includes/footer" . ".php");
?>
</body>

That is by using _main.php as the skeleton of that page and including partials by using include. I do it this way too.

In config.php I have:

$config->prependTemplateFile = '_init.php';
$config->appendTemplateFile = '_main.php';

Which is the way most of us set things up, I guess, because this way into _init.php one can put helper functions, for example, and _main.php can be replaced in the admin to out put something else than HTML (eg. XLM for RSS feed, JSON for public API, etc...). If you use these for header and footer, you loose flexibility. However, your setup should work too so there must be an issue behind the scenes.

 

Edited by szabesz
typo
  • Like 1

Share this post


Link to post
Share on other sites
Quote

 You might want to check the type of line breaks you use, I always use Unix LF so I have no experience with Windows CRLF for example.

I never thought about that and the website is actually hosted on a Windows (IIS) server which might be an issue. However, the CRLF/LF doesn't seem to change any of the output.
Actually, I just tested the exact same code on a UNIX apache server and there it is formatted as expected. So there must be something related to the IIS server. I'll contact the hosting support.

Quote

That said, your code might be "messed up" because prependTemplateFile and appendTemplateFile, so you might want to try constructing your page similar to this:

https://www.pwtuts.com/processwire-tutorials/alternate-template-strategy-using-a-single-output-file/

Thanks a lot for the link, looks very very interesting, I'll try this for my next project.

Quote

If you use these for header and footer, you loose flexibility.

I was already amazed by the flexibility of Processwire and I didn't even know about this way. This just puts flexibility on another level.
Processwire never fails to impress me.

Thanks a lot for your help @szabesz !

  • Like 1

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.

×
×
  • Create New...