HTML templating like PHP templating - php

I know things like these have been asked and answered several times before, is it just that I can't grasp the idea easily or too hard to accept that things are really like this and that.
I know that HTML is used for Front-End where the tedious work is done in the Client, and PHP is working behind the scenes (Server-Side). With so many regulations, instruction, standards, so on and so forth.. I believed I have already confused myself with these stuffs, making things (new and old) hard for me to chew and understand especially when it comes to their best uses...
Anyway, I have created a web application based on the concept of MVC tho I didn't used the strong fundamentals of the topic nor a framework, I separated the Logic, Rules and Design concerns by my own.
Unfortunately, I wound up with some issues similar to which is the right way to do the things, how this should be implemented, etc...
I end up needing to template the HTML, however, since I've used HTML as HTML itself, I end up updating/editing each and every affected file (for. eg. a web page header), unlike when I used PHP before, literally a file with a .php extension, where I can fully utilize templating, however, i read somewhere that it is not a good practice because it breaks the HTML.. so which one should I follow and how can I solve my problem, should I move to .php and then create a template page, or is there a way I could do such with HTML? if there is any, how can it be done?
Please for the meantime, don't point me to frameworks available, I want to understand basic things first before studying frameworks...
Anyone, please...
Edit...
so this is just fine and that it doesn't have any drawbacks...
main.php
<?php php stuffs ?>
<html>
<body>
HTML stuffs and some <?php php stuffs ?>
</body>
</html>

HTML has no templating capability.
It has frames and iframes, but they come with significant drawbacks and only provide include functionality.
You should use a proper templating language. This can run on the client, server or build system.
I'd recommend against running it on the client. It adds an unnecessary dependency that your visitors (including search engine indexers) have to fulfil.
PHP will do the job (it straddles the border of being a programming language and a templating language). My personal preference is for Template-Toolkit.
TT can run in your build system via the ttree utility, or you can run it on your server. There is a tutorial covering how to build websites using it.
If, and when, you move to building websites with more demanding server side requirements, then you can continue to use TT as it is supported but most of the web frameworks in Perl land (e.g. the dancer module for TT and the catalyst module for TT. Note that those links go to the hardcode documentation for the modules, and if you plan to use one of the frameworks you should start with a higher level tutorial)

HTML is a markup language - in other words it can mark up text to display to the user.
It cannot do any of the dynamic type functions you might need in a web application - like updating the date, for example.
So it is best to think of HTML documents, just like you might think of a Word document, a load of text that is displayed to the user.
As soon as you want to start using templates to display dynamic information (stuff from a database, maybe), you're going to need a scripting language. PHP is good for this.
I've had good experience with Smarty - a php templating engine.
On a side note, learning a framework can be a really useful part of the learning the basics. Most frameworks force you to do things in a good way, and sometimes the things they make you write in your code may seem a bit strange or illogical, suddenly one day the penny will drop and you'll realise why what you've been forced to do is sound from an engineering point of view.

You can look # javascript templating. I suggest you to give a try to http://mustache.github.com/

Modest is a template system that's supposed to look and feel like HTML.

The most common way to do HTML templating with PHP, is to use one of these popular templating engines :
Smarty
Twig
Latte
Mustache
Alternatively, you can just put placeholders in your HTML that look something like <% variablename %>. Just load your HTML, do a regex do find all placeholders and replace them with the corresponding variables.
Alternatively, you can load your HTML, parse it as a DOM document and then modify your DOM. I created the library DOM Query to be able to do this with a jQuery-like syntax, but you could use vanilla PHP or one of several other libraries as well.
Alternatively, you can do some HTML templating in frontend with JavaScript. If you want to do HTML templating both on frontend and backend, you might want to consider using Mustache, because Mustache templates can be used both in frontend (with JavaScript) and in backend (with PHP).

Related

Is there anything in PHP like middleman in Ruby?

I've been on a project with a buddy who is leading us with Middleman. We are coding in HAML and SASS and he's obviously a Ruby Dev. I'd like to know if there's ANY type of equivalent for PHP? I'm going to eventually lead a team and I'm much more comfortable with PHP than Ruby.
I'd like to have a layout file (like Zend's layout file)
I'd like to...at one command, convert all of the source files from PHP to static HTML and place those static files in a 'build' folder so we can hand it over to the client.
Anyone know of some cool things out there to make this happen? Thanks a bunch!
A project I work on, www.findbigmail.com, was written completely in PHP to start with and then I did some Ruby/Rails work for a different project, and coming back to PHP was a grind. After using HAML, SCSS and other wonderful things like CSS and JS minify, oh and Compass to build sprites, it was painful to go back to PHP and work again in PHP files with embedded HTML etc.
So, driven by pure slothfulness, I looked around and found MiddleManApp (MM) - after a couple of side trips along the way.
Now we have a very strong separation between what is now a mostly static html site built by MM, with some PHP files that are POSTed to and then redirect back to html pages. Where we need more dynamic behaviour, we've added javascript to the pages and have them call PHP API wrappers around our pre-existing code.
Our site performance has jumped hugely (doh, now its all static html), and its poised to take another jump when the next MiddleMan version comes out with its improved cache-busting abilities inherited from the Rails 3.1 asset pipeline. E.g. we'll be able to reference main.css in our source scripts (which itself is made up of sub-scss files like _index.scss, _pricing.scss) and it will be built with references to main-2348jlk23489kdj.css -- allowing us to set the server to cache for a year and/or deploy many more files to CDN.
Our engineering performance is way up too. We're no longer reluctant to touch UI code for fear of introducing a syntax error into the PHP code. And no more mismatched HTML tags to cause grief. The other PHP developer wasn't familiar with the Ruby/Rails derived toolchain, but has quickly become proficient (though he is a rockstar developer, so that's not too surprising!)
Coming soon is i18n support. Most of that is in MM already and hopefully Javascript support
real-soon-now.
We also explored generating pages from HAML with PHP added to them. We decided it was probably quite simple - e.g. add a ":php" tag to the HAML pipeline and then use .php partials as needed. But, we found that between Javascript and wrapping the existing PHP code as an "engine API", we were able to keep the codebases neatly separated -- which we found we prefer overall.
I hope this helps! Happy to explain more.
There is one for PHP called Piecrust.
I ended up choosing Middleman for the bundled coffeescript, sass, etc., but Piecrust is well done.
http://bolt80.com/piecrust/
PHP can render static HTML from PHP code quite easily:
Easiest way to convert a PHP page to static HTML page
Generate HTML Static Pages from Dynamic Php Pages
PHP - How to programmatically bake out static HTML file?
You could wire up something with existing template systems like Twig or use PHP Markdown to more or less mimic what Middleman is doing and create static HTML pages from your source files.
EDIT: As Hari K T mentioned above, http://www.phrozn.info/en/ does exactly this.

What architecture should I use for writing my first dynamic website in PHP? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I just want to build my first dynamic Website. I want to use PHP, MYSQL, AJAX, HTML, CSS
I have some beginner Questions:
Should the Header and Navigation Bar excluded in a header.php and print out with echo?
Should the design tags in the echo in php (like: <a>1 Test test</a>) or only return the the data
Is there a good example for making dynamic websites?
My main problem is that i don't know how to make a clear structure. Where to make the right design (print out in the php ?)
If it is really your first website, I'd actually recommend using nothing in terms of frameworks. This buys you some time to get comfortable with HTML/CSS, SQL and PHP, without overloading you with higher-level principles such as MVC (model/view/controller) and others. I'm mostly concerned that starting with a framework right away makes the learning curve to steep, and skips over things such as getting comfortable with the programming language you'll be using.
You'll eventually make a mess with way, but this will only make you appreciate the frameworks more; you can then make the transition to using a framework such as CodeIgniter, Symfony or CakePHP (or others, because there's a whole bunch more).
Other frameworks that I really like working with are Play! for Java, and Rails for Ruby. Since you stated you're a beginner, you might consider these as well.
Well, to answer all your questions at once.
The only technology you need is template.
Template is a typical PHP script, however, consists mostly of pure HTML, with some PHP code only to display dynamically generated data.
Create a main site template contains both header and navigation bar and footer everything else excluding actual page content.
Then create separate pages ("sections" of your site: news.php, links.php, etc.)
But make every page of 2 parts: getting data part and displaying data part.
While getting data, not a single character should be printed out.
If some errors occurred, display an error page.
Once you get all your data with no errors - it's time to include a main template.
A typical script may look like
<?
//include our settings, connect to database etc.
include dirname($_SERVER['DOCUMENT_ROOT']).'/cfg/settings.php';
//getting required data
$DATA=dbgetarr("SELECT * FROM links");
// setting title for using in the main template
$pagetitle = "Links to friend sites";
//etc
//set page template filename
$tpl = "links.tpl.php";
//and then finally call a template:
include "main.tpl.php";
?>
where main.tpl.php is your main site template, including common parts, like header, footer, menu etc:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>My site. <?=$pagetitle?></title>
</head>
<body>
<div id="page">
<? include $tpl ?>
</div>
</body>
</html>
and links.tpl.php is the actual page template:
<h2><?=$pagetitle?></h2>
<ul>
<? foreach($DATA as $row): ?>
<li><?=$row['name']?></li>
<? endforeach ?>
<ul>
Eventually you may come to more complex designs, like with front controller one, but for the first site this one is both easy and powerful.
Yes, I do recommend you include header and navbar scripts from another file.. where you can maintain them independently. I think that is pretty important.
I recommend you echo/print html from php, rather than insert php into html (easier when doing things like parsing $_GET/$_POST etc)
I recommend that you create a template, and another script which has functions that print (or echo) the html tags, header, footer, title bar, navbar etc. Just include the script with the functions and all your pages can have the following structure:
<?php
include 'html_display_functions.php';
/* put lines here to parse $_GET and $_POST, session_start()/$_SESSION,etc
if needed */
print_html_pre_content();
print '<p>Hello, world! or other content.</p>';
print_html_post_content();
?>
I have found this to be pretty clean, and it is easy to add functionality when you get to messing around with $_GET, $_POST and $_SESSION, etc.
I'd suggest to use some template system (Smarty would be good).
It does not really matter where do you put your header and navigation bar at first glance. When do you need to exclude Navigation bar and store it separately? When you want to have ability to include different nav. bars in different parts of your website.
For example I have a website with several subdomains: about.website.dev, special.website.dev and, let's say, terms.website.dev
At about.website.dev my navigation bar's entries will be: "Who I am", "What do I do", "How cool am I"; at special.website.dev: "Goods", "Solutions", "Tips" , etc.
Your navigation bar's template is the same: just a loop though all entries, but content differs. In this case you separate navigation bar from header. If you don't use templates, you just create three files (in this case): about.nav.php, special.nav.php and terms.nav.php and then you just include appropriate navigation bar.
If your nav. bar is all the same everywhere on your website, you can store it in header.php. Once you need to separate, it will not be difficult, but still I'd suggest to use templates though just to get used to "proper website development".
Take a look at different templating systems like Smarty or Savant. I, personally, like Django's (python) templating system most. And get used to separate your view and business logic.
IMHO, you would be better off having a look at a php-based web application framework. such as the list at http://en.wikipedia.org/wiki/Comparison_of_web_application_frameworks#PHP
Even though it may be a little more to learn upfront (the framework as well as php), they all have solid enough structures to develop dynamic websites with. Find one that is light enough and has good tutorials and you'll find yourself learning the php language along the way. I believe this will be easier than just using raw php at the beginning stage.
When you know more you can then make a judgement call on which frameworks you prefer and suit your needs or coding style or even revert back to raw php.
If you want a good book on the subject, try
MySQL/PHP Database Applications by Brad Bulger, Jay Greenspan and David Wall
What you are asking is pretty much a matter of taste. The more complex your application will be, the more work should go into an elaborate and maintainable structure.
My opinion is: Learn the basics first and then look at frameworks. It makes it a lot easier if you understand what happens under the hood.
Try Agile Toolkit, probably the easiest PHP UI framework to get started with designed for web software.
You'll step over many problems. http://agiletoolkit.org
Depending of the choice of framework/plain PHP, you should do it in accordance with their practices. For instance in Agile Toolkit you use templates, so you put your header and footer into templates/jui/shared.html file. It's explained in the first screencast.
If you reinvent the wheel and go ahead with plain PHP, then you should do better do include 'header.php'; . Good framework lets you NOT learn about inner workings of web software. Bad framework needs you to know everything anyway.
There's a lot of good answers here already - but just to add....
Do split functionality into separate include files - and use a consistent way of locating these files.
Do find a good PHP coding style and stick to it. e.g. horde, PEAR
Don't have code or HTML executed inline in include files - it should only do something when you specifically invoke it from your controlling script.
If you are including files which generate HTML, make sure they provide functionality for closing any tags they open. i.e. not just a 'header.php'
Since CSS and Javascript files should not be directly declared outside the HEAD of the HTML document do look at ways by which invoked functionality can add these into an existing HTML document - one obvious solution is to use a templating system combined with output buffering but you can also inject additional JS and CSS files into the HEAD section later in the document by using javascript.
Use MVC - http://www.yiiframework.com/doc/guide/1.1/en/basics.mvc
See Yii-framework http://yiiframework.com, it has all you need :)

Is there a html-only templates system for php?

I have started coding in clojure, and I'm really impressed by Enlive. One thing that I really like about it is that Enlive uses html-only templates. So a template is a file with html in it, ending in .html, simple as that. It gets parsed into a dom tree and then that dom tree is manipulated by clojure/enlive, combined, made dynamic, etc. No syntax in the html template files, a beautifully clean separation.
Another example of a similar system, done via javascript, is PURE.
Is there anything like that in php?
Or, in general, any ways of doing html-only templating?
Fascinated to hear of Enlive. I've been thinking about this concept for a few years and have hacked together something in PHP that shares some principles: templates are pure HTML, and you "fill" them by addressing content to a specific node in the document using CSS or XPath.
$t = new Template('yourfile.html');
$t->fill('#nav',$someMarkup);
$t->fill('#header',$otherMarkup);
I also experimented with throwing together some provisions for separating the content out into a "stylesheet" of sorts... well, "stylesheet" is the wrong word. I'm calling them content-addressing sheets (the project is called CAST, for content-addressed-style-templating). A CAS looks like you might expect:
.col #foot {
content: 'foot';
}
#content {
content: file_get_contents('pangolin.txt');
}
The values of content are assumed to be PHP expressions. There's some provision for setting up PHP that applies across selectors, too.
Take a run of the cssfill.php script that's in the tarball (best invocation is probably ./cssfill.php pangolin.cas pangolin.html, you might have to change the path to your php interpreter inside cssfill.php), take a look at the output, compare with the input files.
If this post generates any enthusiasm for the idea in you, feel free to let me know. I've been wondering whether this was a crazy idea or whether it has a place, if it does, I'd be happy to turn it into a thoughtfully released open source project as opposed to a tarball randomly tossed onto the internet.
You can check phptal.org. It's a template engine for PHP that uses HTML tags.
But it's not that fast.
You can also check other projects like twig-project.org witch is waaay faster.
Checkout PHPTAL.
PHPTAL is a XML/XHTML template library for PHP5 which provides compiled templates and fine-grained caching.
Templates are defined in pure XML/HTML markup.
<div class="item" tal:repeat="item itemsArray">
<span tal:condition="item/hasDate" tal:replace="item/getDate"/>
<a href="${item/getUrl}" tal:content="item/getTitle"/>
<p tal:content="value/getContent"/>
</div>
Interesting starts. But I'm impressed why we can't have diferent template with specimen text to change the view and the different state of elements - and extract the code to create exiting template systems or just fill it up with content. Find the workflow feels so broken an complicate - don't like mixing html with php / js nor writing abstract template systems. Need to much brain - to much commication without easy visualisations.
I think Psttt! templating engine for php is exactly what are you looking for, it keeps your html template intact allowing you to better reuse your htmls.
full source code here http://github.com/givanz/psttt

separating php and html... why?

So I have seen some comments on various web sites, pages, and questions I have asked about separating php and html.
I assume this means doing this:
<?php
myPhpStuff();
?>
<html>
<?php
morePhpStuff();
?>
Rather than:
<?php
doPhpStuff();
echo '<html>';
?>
But why does this matter? Is it really important to do or is it a preference?
Also it seems like when I started using PHP doing something like breaking out of PHP in a while loop would cause errors. Perhaps this is not true anymore or never was.
I made a small example with this concept but to me it seems so messy:
<?php
$cookies = 100;
while($cookies > 0)
{
$cookies = $cookies -1;
?>
<b>Fatty has </b><?php echo $cookies; ?> <b>cookies left.</b><br>
<?php
}
?>
Are there instances when it is just better to have the HTML inside the PHP?
<?php
$cookies = 100;
while($cookies > 0)
{
$cookies = $cookies -1;
echo'<b>Fatty has </b> '.$cookies.' <b>cookies left.</b><br>';
}
?>
When people talk about separating PHP and HTML they are probably referring to the practice of separating a website's presentation from the code that is used to generate it.
For example, say you had a DVD rental website and on the homepage you showed a list of available DVDs. You need to do several things: get DVD data from a database, extract and/or format that data and maybe mix some data from several tables. format it for output, combine the DVD data with HTML to create the webpage the user is going to see in their browser.
It is good practice to separate the HTML generation from the rest of the code, this means you can easily change your HTML output (presentation) without having to change the business logic (the reading and manipulation of data). And the opposite is true, you can change your logic, or even your database, without having to change your HTML.
A common pattern for this is called MVC (model view controller).
You might also want to look at the Smarty library - it's a widely used PHP library for separating presentation and logic.
Let's make it clear what is not separation
you switch from php mode to html mode
you use print or echo statements to write out html code
you use small php snipplets inside html files
If you do this, there is no separation at all, no matter if you escape from php to html blocks or do it the other way and put php code into html.
Have a look at a good templating engine, there are a plenty of reasons in the "why use ...." parts of the manuals. I'd suggert www.smarty.net especially http://www.smarty.net/whyuse.php
It will answer all your questions now you have.
It is very important to separate application logic from presentation logic in projects. The benefits include:
Readability: Your code will be much easier to read if it does not mix PHP and HTML. Also, HTML can become difficult to read if its stored and escaped in PHP strings.
Reusability: If you hard-code HTML strings within PHP code, the code will be very specifc to your project and it won't be possible to reuse your code in later projects. On the other hand, if you write small functions that do one task at a time, and put HTML into separate template files, reusing your code in future projects will be possible and much easier.
Working in a team: If you are working in a team that contains developers and designers, separation of application logic and presentation templates will be advantageous to both. Developers will be able to work on the application without worrying about the presentation, and designers (who don't necessarily know PHP very will) will be able to create and update templates without messing with PHP code.
for pages that contain a lot of HTML, embedding PHP code into the page could be easier. this is one of the first intentions behind PHP. anyway when you are developing an application with lots and lots of logic, different types of connectivity, data manipulation, ... your PHP code gets too complicated if you want to just embed them in the same pages that are shown to users. and then the story of maintenance begins. how are you going to change something in the code, fix a bug, add a new feature?
the best way is to separate your logic (where most of the code is PHP) in different files (even directories) from your page files (where most of the code is HTML, XML, CSV, ...).
this has been a concern for developers for so many years and there are recommendations to handle these general problems, that are called design patterns.
since not everyone has the experience, and can apply these design patterns into his application, some experienced developers create Frameworks, that will help other developers to use all the knowledge and experience laying in the hear of that framework.
when you look at toady's most used PHP frameworks, you see that all of them put code into PHP Classes in special directories, make configurations, and .... in none of these files you see a line of HTML. but there are special files that are used to show the results to users, and they have a lot of HTML, so you can embed your PHP values inside those HTML pages to show to users. but remember that these values are not calculated on the same page, they are results of a lot of other PHP codes, written in other PHP files that have no HTML in them.
I find it preferable to separate application logic from the view file (done well with CodeIgniter framework with MVC) as it leaves code looking relatively tidy and understandable. I have also found that separating the two leaves less margin for PHP errors, if the HTML elements are separated from the PHP there is a smaller amount of PHP that can go wrong.
Ultimately I believe it is down to preference however I feel that separation has the following pros:
Tidier Code
Less of an Error Margin
Easy to Interpret
Easier to change HTML elements
Easier to changed Application Logic
Faster Loading (HTML is not going from Parser->Browser it goes straight to browser)
However some cons may be:
It only works in PHP5 (I Believe, could be wrong, correct if needed)
It may not be what one is used to
Untidy if done incorrectly (without indentation etc, however this is the same with anything)
But as you can see, the pros outweigh said cons. Try not to mix the two also, some separation and some intergration - this may get confusing for yourself and other developers that work with you.
I hope this helped.
Benefits of the first method (separating PHP and HTML):
You don't need to escape characters
It's also possible for code editors
to highlight/indent the markup.
It's arguably easier to read
There is no downside to this method,
compared to the second method.
Functionally: they both will work, so ultimately it is a preference.
Yet, you might consider that comments are a preference as well, your code would compile and run exactly the same without comments. However most people would agree comments are essential to writing and maintaining good code. I see this as being a similar subject matter. In the long run it will make it easier to read and maintain the code it if the two are separated.
So is it important? I would say Yes.
I kick off with: the first one you can open in a WYSIWYG editor, and still see some markup, which might makes it easier to maintain.
It says that what you put in echo '' it is first processed by the programming language and then sent to the browser, but if you directly put there html code without php, that code will load faster because there is no programming involved.
And the second reason as people above said is that you should have your 'large programming code' stored separately of the html code, and in the html code just put some calls to print results like 'echo $variable'. Or use a template engine like Smarty (like I do).
Best regards,
Alexandru.
Ouch!
All of the examples in your question are perfectly impossible to read. I'd say, you do yourself and those, who might read your code a great favour and use a template engine of sorts, say, Smarty. It is extremely easy to set up and use and it WILL separate your code from presentation. It doesn't require you to put everything in classes, it just makes sure, that your logic is in one file and presentation - in another one.
I don't know how in php but in asp.net separation has the following advantages.
1. separated code is easy to understand and develop
2. designer can work in html in the same time developer can write a code

PHP coding standards

I've been looking for some guidelines on how to layout PHP code. I've found some good references, such as the following:
http://www.dagbladet.no/development/phpcodingstandard/
and this question on SO.
However, none of that quite gets to what I'm specifically wondering about, which is the integration of HTML and PHP. For example:
Is it OK to have a PHP file that starts out with HTML tags and only has PHP inserted where needed? Or should you just have one section of PHP code that contains everything?
If you have a chunk of PHP code in the middle of which is a set of echo's that just output a fixed bit of HTML, is it better to break out of PHP and just put in the HTML directly?
Should functions all be defined in dedicated PHP files, or is it OK to define a bunch of functions at the top of a file and call them later on in that same file?
There are probably other questions I'd like to ask, but really I'm looking for someone to point me at some kind of resource online that offers guidance on the general idea of how HTML and PHP should be combined together.
Combining programming code and output data (including HTML) is IMHO a very bad idea. Most of the PHP gurus I know use a template engine such as Smarty to help keep the two things separate.
There's really not a single, common standard for these things. Most languages are more restrictive than PHP in this sense.
In the later years, a lot of so-called frameworks have emerged, and amongst other things they define a set of rules for everything from naming over where to place files and to which style your code should follow. There are several frameworks around, so you can't really pick one and call it the standard. However, most frameworks have a subset of commonality. For example, most follows some variant of the PEAR Coding Standards.
I usually try and follow the standards that are set by the language's core libraries.... oh wait.
Seriously through - you should try and follow the MVC pattern in any web application as it is pretty much standard practice regardless of language. In PHP this can be achieved in a quick-and-dirty way by treating index.php as your controller and separating data logic and presentation by file. This small step will at least let you move your code to a full featured framework when and if you choose.
Use a template engine when you can. If you haven't learned one, or don't want the overhead (which is minimal), use practices that cause you to have quick-and-dirty templating:
Functions that do not display anything have no place in a file that does display something.
Print variables, not HTML. Whenever outputting HTML, break out of the PHP and write HTML with print statements to handle any small details that are needed (actions for forms, IDs for controls, etc.).
Remember, when you include a file that breaks out of the PHP to print content, that will be treated the same as if you do it in the main file. So you can create simple templates that just included PHP files, and those files will print variables in the right places. Your index.php (or whatever) does all the real work, but all the display is done by the secondary "template".
Many PHP tutorials intermix logic and display code. It took me years to break the bad habits that encouraged in me. In my experience you can't separate things too much in PHP, and entropy will pull you towards intermixed code if you don't fight it.
Coding standards should be more than how to layout your syntax, but sadly that's what they tend to be in PHP.
FWIW, phc will pretty print your code in the Zend style.

Categories