Simple web page layout and templating in PHP - php

In the past I've written sites in ASP.NET just to get nice reusable templating via master pages (layouts) and user controls (partials). I'm talking about sites that have no more complicated code in them than simple variable substitution in templates - I'm just using it to keep my HTML organized. It's great to be able to define the basic layout of your page in one file, and then just fill in the holes for each individual page, re-using some common bits as user controls.
However, I'd rather not continue using Windows hosting, so I'd like to write static pages in PHP, which runs everywhere. In the past I've written myself a poor-man's user control for PHP that just unpacks an array and includes a template, but that's clunky and still requires me to put PHP includes all over my pages. I feel like Smarty or one of the other big templating languages for PHP is overkill for just organizing some "static" pages.
I've considered just doing the pages in Ruby on Rails because I really like HAML/SASS and the layout/partial model, but having a whole rails app for static content seems silly. But I haven't found anything that seems just right in PHP. Can any PHP gurus recommend anything? I want something more sophisticated than "include" but I don't really need much. That said, something that could give me layouts/partials AND HAML/SASS would be heaven. I've looked at phammable but it doesn't look like it solves the layout/partial problem.
Again, I'm not looking for something as complex as Smarty, and I don't want a full CMS. I just want something that will let me properly modularize the HTML of my site. We're talking one step beyond static HTML here.

Zend_View supports layouts, partials and placeholders. Also checkout a new templating language called Dwoo which is similar to Smarty but also takes some ideas from Django templating. And finally, Calypso which is a Django template language clone for PHP

If your looking for something simple I would recommended PHP Template Inheritance. Then you can continue to code in straight php.

I just want something that will let me
properly modularize the HTML of my
site.
Look at http://code.google.com/p/hoduli/
With that simple tool you'll be able to write like this:
<h:define name="header">
some header contents
</h:define>
...
<h:header />
<h:include file="middle_part.php" />
<h:footer>
some ...
</h:footer>

I would suggest to you to look at Drupal and its Block templating model. I think its just what you need.

Stacey is about what I was looking for in terms of a simple PHP templating library for static sites.
On the Ruby side, there's StaticMatic, which doesn't even require Ruby support on the server since it generates the whole static site. Very nice (especially since it uses HAML) but you can't have any dynamic elements at all.

From what i understand, you don't want a full fledged cms and no overkill templating engine like Smarty. Php is a templating system and if you want to properly modularize it, that's up to you.
But i understand, those php tags between your html doesn't look pretty. (Although using shorttags minimizes this...)
You can always use PEAR Templating system, it's available by default on most php installations.
I would also recommend the CodeIgniter MCV framework because it's really lightweight. You choose which libraries get autoloaded.

About six months ago, I started using the Zend Framework. I got used to working with layouts and partials, and never wanted to go back creating sites without it. But for small sites, ZF is just too bulky. It's overkill to use ZF for a site that could be done in HTML.
Check out EuropaPHP. It's a super lightweight, PHP based layout framework. It's brand new as a framework, but so far, I like it a lot! It allows me to use layouts and doesn't require a huge library and strict rules to achieve the same results.

Maybe you should take a look at some content management systems. Drupal is famous in PHP.

Drupal really is a simple and extensible CMS. There is a learning curve, but it's strengths are that is starts small out of the box and can grow with your needs and the community is pretty tight about the quality of the code that's written (though I personally find that some of the modules get a little two function happy).
They have a simple stripped down version of the Zen theme, that lets you create the HTML you want to use. Time spent learning this CMS is time well spent, especially if PHP is already your native language.

Related

Share templates between React/Vue.js and PHP + HAML

I'm choosing frameworks for my next project and got stuck on a tricky problem: How to share templates between server-side PHP and client-side Javascript?
On server, my application is going to be written in PHP, using Symfony, Twig, and MtHAML. I have few templates as an early GUI prototype and I really like HAML as it cuts my templates in half.
On client, I would like to use Vue.js or React or something like that (and say bye to jQuery spaghetti monsters). I haven't decided what to use here yet. I like ES6 class syntax. The client side is going to be a set of relatively simple SPAs — old-school standalone pages with some JS to make them more interactive. Therefore, there will be no routing nor manipulating browser history on client, but still, I want to update already loaded page here and there.
So, I will need to use templates at two places: server-side in PHP and client-side in Javascript. The question is, how to share one template on both sides?
I'm thinking about compiling the HAML templates with Dust.js/php (Mustache is too dumb) into Javascript or some similar aproach. Another way could be to render Vue templates from HAML (Gitlab does that) and somehow pre/post-process them into PHP templates. But I'm sure there were many people dealing with this problem too. Unfortunately, most resources on the Web are outdated or very messy. Is there some ready-to-use sollution?
I was solving similar problem before and the best solution for me became to use Symfony to build a decent API and then some js framework for frontend. Juggling with templates between two environments was a real pain. Maybe you'll choose different approach, just a suggestion from me...

Layout/Decoration framework for PHP?

A little of my background... I'm fairly new to PHP as I primarily develop in Java. PHP interests me, thus I decided to spend my free time learning it by trying to make one of my relatively static websites more dynamic using PHP.
Right now, I'm have a problem in decorating all the web pages... not really a problem, but it bugs me. I know I can include the header and footer files in every page, but I'm wondering if PHP has some sort of web-based layout/decoration framework?
In Java, I use Sitemesh to decorate my web pages without the need for me to explicitly include the header/footer files. I'm hoping I can do the same in PHP too.
If you have abundance of experience developing web applications in PHP, can you please share some of your knowledge with me here? I'm interested to know the techniques you use to easily decorate your web pages and to change the page layout in the future.
I greatly appreciate your tips and ideas. Thanks much.
PHP doesn't neccessarily have a 'decor' framework, but more generally it has many MVC based frameworks for the language itself. Many of these include 'templating' elements that allow for such headers, footers, partial layout content, etc...
Some of these are
Codeigniter (My personal Choice)
Kohana
Zend
Symphony
Generally, people will recommend what they use, and most of the time you can't tell if they use it because they like it, or like it because they use it. I recommend consulting the specific frameworks documentation to get a feel for whether or not it fits your needs.
EDIT :
After a second read of your question, I also thought you might look into more simple CMS solutions. While you could accomplish what you want to do with any of these frameworks, it might be less work to use a CMS that uses a templating engine, if all you want to do is manage content and the way it looks. The frameworks listed above are a bit more adept and building web applications (for comparison, a CMS is a web application).
Wordpress
ExpressionEngine (By the makers of Codeigniter)
Drupal
I use a main template view for HTML pages. This includes the header and footer, but the middle has a <?php echo $primaryView; ?>.
I can change the $primaryView depending on what page needs to be shown.
The MVC pattern is very useful with web development.

A Question About Embedding HTML In PHP

Some time ago I read a posting on a board where the person was talking poorly about people that have HTML embedded/within their PHP. I do quite a bit of PHP development but I still interleave HTML and PHP in the same document. Is there a better way to do this, am I doing it wrong? I know that in JSP/JSF they use an XML document with namespaces to insert their HTML code so I was wondering if there was a similar function that PHP uses that I should be taking advantage of.
Thanks for taking the time to read. :-)
PHP was originally designed as a templatng language. It sort of evolved over time to give it more power, but that doesn't mean you can't still use it for templating. A few <?=$var?>s here an there isn't too awful; hardly worse than {{var}} or whatever other syntax these new fangled engines offer.
The thing you really should do though, is take as much "business logic" out of the "views" as possible. That means the only code on the display page should be stuff that's actually relevant to how the page looks. No database updates or stuff like that. If you do this, then it should have nice, clean, maintainable pages :) No framework or anything necessary.
That said, I'd only do this for smaller apps. Template engines don't hurt either ;) Especially if your designer is a non-programmer.
Yes. You could separate the presentation code into different files. They call them views, or templates. There are a pretty bunch of templating engines you could use: there's smarty, there's Twig, and a lot of others.
You could also use a full-featured framework, like Zend, Symfony, CakePHP, Code Igniter etc. There's a lot of lists floating around.
Best regards,
T.
You should consider using a template engine such as Smarty instead of mixing logic and presentation. This clears up both code and page, and forces you to define your requirements for the page clearly before invoking the template engine.

Why use a templating engine with a framework?

I recently discovered the PHP framework Kohana (which is awesome) and was reading a thread about using it in conjunction with a templating engine such as Smarty or Twig. My question is why bother? Surely an MVC framework, by definition, is a templating engine. Even "raw" PHP is, arguably, a templating engine. What possible benefits are there of adding another level of abstraction on top of what's already present in a framework such as Kohana?
EDIT -
I realise that an MVC framework isn't the same thing as a templating engine, but surely the V part does the same job? Perhaps a better way of phrasing things would be; why add an templating engine on top of the V part of an MVC framework?
I have two really good reasons I can think of for doing this...
Creating markup that is repeated throughout the site in a consistent format is easier, plus you can update it later without a lot of grepping.
If this is for a real company, the people determining content aren't likely to be really familiar with HTML, much less PHP. Having a simple template language that keeps styles looking the right way and generates valid markup without much code knowledge is really handy.
Firstly, raw PHP is NOT a templating engine.
Next, MVC framework defines that the framework is split into Model, View and Control. It does not mean that the framework has a template engine, though the View may be integrated with a native or external template engine. Thus the framework may or may not have a templating engine.
Thirdly, View != template. View is only referring to how data is displayed - there is no template involved usually, whereas template engine refers to a piece of code able to put data nicely into templates - which you can greatly reduce the need to modify all files when you can modify them in the templates
Lastly, framework users may prefer to use a more common templating engine such as Smarty over the native template engine in the framework. You do not need to learn the new tags in the native template engine.
Unless you allow for short tags,
{$foo}
is much more readable than
<?php echo $foo; ?>
Multiplied over a large project, it adds up.
One big reason why you would want a separate template engine is because raw PHP is a bit too much for the presentation of your site. If it's just you making your site, and you have a good idea about how the site's templates aught to fit together, then this isn't really a downside, but for larger projects, it gets in the way.
If your project has outgrown a single developer, or if you want to add designer even before that, PHP is probably too hard a language to express the presentation in. Purpose built template languages are at the advantage because they are simple, and don't give you so-much rope as to hang yourself.
Larger projects, even when they don't require much input from multiple developers, can make the free-form of plain PHP a bit unwieldy. the purpose built template engine provides (or enforces) a basic structure to how each template fits with the rest.
Mauris has already covered why MVC != template engine, but I would like to add that the more powerful the template engine is, the cleaner and more concise your templates are. This makes it especially easy for people who are not familiar with PHP to edit them (e.g.: if a designer/front end developer needs to edit the HTML). In general, MVC's don't boast this sort of functionality.
Take a look at this example from Smarty. I've never used the engine and answering this question is the first time that I've ever seen its markup, but I can already tell exactly what its doing.
Further, the amount of code that you have to write is noticeably less since Smarty and other engines take care of mundane things for you like alternate row colors and alternate content for empty data sets in the first example, and silly things like formatting <select> lists in this example.
MVC implements the management of PHP templates, if you work in a team with web designers could be better to use HTML templates. Smarty and Twig are famous and good.
Anyway just choose the template engine you feel more comfy with.

PHP vs template engine [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 9 years ago.
Improve this question
I'm currently having a discussion about the choice between PHP as a template engine versus a template engine on top of PHP.
What is your choice, and why?
I say why use another template engine when PHP is a template engine itself.
For template engines:
Added security for end-user customization. Themes in pure PHP have unconstrained ability to cause harm to a user and their installation. Thus a template engine removes that risk, if it is a good one.
Ease of use for non-programmers, such as graphic artists or web designers.
For plain-php:
The speed of pure PHP cannot be matched by any template engine built atop it.
The full power of PHP is available to the output, and not just an interpreted or filtered portion.
I prefer PHP itself if at all possible. And most folks don't want to hack your software by making a custom theme, so it's easy to take a cursory read and investigate its security. That said, I am the "between guy" who does both templating and programming, and even some graphic arts; my skillset differs from a strict programmer and a strict artist/designer.
I found that when I introduced Smarty, it was fairly straight forward to get web designers to produce HTML with smarty variables. The folks on the programming team now concentrate on more back-end work, that is, the production of the content of the Smarty variables.
This has shortened the development lifecycle, with work being able to be split between more people, and has ultimately led to better designs.
Well, it's just my opinion, but template engines suck. You have to first understand how the template engine is implemented and then learn how to use it. It seems just wasted time, because PHP alone does it best and offers much more flexibility.
The following reasons apply:
Separating your application into templates with an engine makes your application less vulnerable to halting code errors
Using templates can give you greater flexibility in the future when refactoring because the namespace won't be directly built into the application
Using templates encourages (forces) developers to keep business logic and code OUT of the presentation layer.
Using templates it is easier to mock up datasets and pass them to a template engine and get a preview of what the site will look like with data
PHP is not a template engine, but a language that can be used to write templates, or template engines. A template engine is not just a language, but also the programming API that allows the scripts to locate, organize templates or assign the data from the script to them. Pure PHP offers you absolutely nothing - it is just a language. Instead, you should take such libraries, as Zend_View in Zend Framework to comparisons (basically, it works exactly in the same way, as Smarty, except that it uses PHP to write templates). You should ask whether you should use a template engine with PHP or something else as a template language.
When it comes to templating languages themselves, then well... ordinary loops and conditions are enough to write templates, but this "enough" does not mean that it is easy, comfortable, efficient or flexible. PHP does not offer anything special for template designers, but many "templating languages" (like Smarty) provide just a limited subset of PHP, so I'm not surprised that programmers choose PHP. At least they can write functions and use OOP which is too massive for this (in my opinion), but does work and really helps.
The point is that custom templating languages are not limited with PHP drawbacks, but their designers unsually do not see it, claiming that "displaying variables and a loop is enough". The possible areas, where templating languages could be much more effective:
Form displaying and rendering (I haven't seen any framework with PHP as a templating language that provided an easy, flexible and generic system for customizing the form look).
Understanding the HTML/XML document structure.
Automatic XSS injection filters.
Solving various common problems in the presentation layer (i.e. customizing the look of the pagination system, displaying the data in columns etc.)
Template portability and true separation of the application logic and implementation details from the templates.
Examples of templating languages that follow this way are mentioned above PHPTAL and Open Power Template 2. Some similar ideas can be also found in TinyButStrong, but unfortunately this template engine is extremely slow.
Using a template engine can be helpful if you have a non-programmer doing the templates. In many cases, the simplified template language can be easier for a non-programmer to pick up than PHP itself.
That said, I find myself moving away from using templates when it's just me (or me and other developers).
PHP as template engine will not complain when you mix up your HTML syntax. It will let you forget to close tags, mis-nest them, etc.
PHP's output is not escaped by default, so unless you remember to rigorously add htmlspecialchars() everywhere, your site will have HTML injection (XSS) vulnerabilities.
<p>Hello <?= $name ?></b>
<!-- Simple template full of errors -->
These problems are much worse when you try to generate XHTML properly. It's not that you can't do that with plain PHP - of course you can - but that requires more effort and diligence.
That's why my recommendation is PHPTAL. OPT2 is OK too.
Savant is what you are looking for. Its a nice wrapper class that allows you to use the PHP operators in your templates instead of interpreting an new template language on top of PHP.
Pros:
It makes sense not to add extra work to the system.
No learning curve for developers
If you everyone is disciplined then this is the way to go. (Savant)
Cons:
Although Savant encourages you to separate properly it doesn't force the developer to separate business logic from development code. I have a rule that should never be broken. You can only output variables, use conditions and loops in your templates. You must never allow a developer to create variables in the template. Unfortunately developers never seem to do this no matter how many times you tell them. So, using a engine like Smarty then becomes worth it because the developers are forced to completely keep business and design apart.
If I'm doing a project for myself or one that doesn't have many developers I tend to use Savant. If its a project that is much bigger than just me then in the Architecture I'll go for something like Smarty.
Either way, the separation in the code is important weather you use Savant or Smarty. I'm sure there are other good options out there too.
PHP is perfectly suitable for most tasks, but a templating engine can help a project to scale more easily.
Off the shelf ones like Smarty or PHPTAL are great if you do not have the time to roll your own (and do not require more than they offer). Also, you can fairly easily replace/modify them with your own implementation later on if you find you need something more specialised.
I've personally had a good experience with PHPTAL, primarily because it keeps out of your way and is simple.
I found building a light-weight template engine in PHP worked best for us. Allows for good code separation, and our graphic designer could learn a few simple rules to follow, but most writes HTML/CSS not PHP. I can write the heavy lifting code without having the think much about the interface.
The following article sum-up the different points of view about Template Engines for PHP.
Doing PHP templates of the third kind
http://www.tinybutstrong.com/article_3rd_kind.html
My choice for any new project would probably be to simply use the templating capabilities of PHP, possibly in combination with an MVC framework, instead of using another templating engine. After all, for code simplicity or cleanliness of separation, it doesn't really matter whether you have {$myVar} or <?= $myVar ?> in your code. More complex templating features such as conditions, loops, or backend-technologies such as caching can be handled just as well (or better) by PHP or the MVC framework.
I have used both approaches (with and without a templating engine), but only in personal projects, never in team projects, so perhaps there are compelling arguments for the use of a templating engine in such a setting.
I don't know whether it is due VirtueMart, Joomla or the concept of templates in PHP, but adjusting VirtueMart to your own graphic theme is PURE HELL. (I'm not talking about plain CSS-styling.)
PHP isn't a templating engine its a scripting language.
PHP coding features evolved, designing feature are the same, that's why if you work in a team with designers and developer you need a template engine to parallelize the job, and let the designers work with HTML.
My personal choice is Raintpl, because is lightweight, friendly and fast
here a benchmark can help you choose (also smarty and savant are nice!):
http://www.raintpl.com/PHP-Template-Engines-Speed-Test/
If I had to spend the time learning a standalone template engine, I would rather spend the time learning a Framework instead. My choice is to go with Zend Framework, which when implemented using an MVC approach, provides you with the power of the framework, along with the native templating capability of PHP itself.
Since I asked this question, I have came across mustache. This is a logic-less template language.
So this is not the same as PHP or smarty where you have the possibility to add all sorts of logic to you template, but forces you to keep all the logic in something like view models.
This seems to me a better option then switching to template language where logic is still possible.
I use a template engine in PHP because I prefer to have a high degree of separation between business logic and presentation logic. Web programming is much easier when your PHP (or any other programming language) doesn't have HTML scattered throughout. This is Microsoft's code behind is so popular.
I use a template engine called KudzuPHP. It is a port of my KudzuASP for Classic ASP. It differs from many template engines in that the code that hosts the business rules and logic becomes an event handler for the template engine after the template engine is invoked. This approach allows you to modify the templates (moving large blocks of presentation) without requiring you to modify the code of the PHP code.
KudzuPHP contains it's own library system and writing new extension tags and libraries is very easy.
You can find KudzuPHP here: http://www.andrewfriedl.com/downloads/
If you want a version embedded in a Wordpress plugin that allows you to code against the Wordpress API without PHP go top Wordpress.org and search the plugins for "Kazoo".
currently, it the most faster and easier to use. After making a suite of benchmark on PHP templates engines, twig comes in the second place just after native php language.
I wrote a blog post about this recently.
For the security sake alone, definitely use a templating engine ( Twig is secure ).
A good templating engine (such as Twig) offers:
Security (most important what so ever )
Not verbose (like php)
More templating features

Categories