Please explain what a template engine is, and what it is used for. What are the paragraphs below trying to say? I don't follow the author's explanation.
Although CodeIgniter does come with a simple template parser that can
be optionally used, it does not force you to use one. Template engines
simply can not match the performance of native PHP, and the syntax
that must be learned to use a template engine is usually only
marginally easier than learning the basics of PHP. Consider this block
of PHP code:
<ul>
<?php foreach ($addressbook as $name):?>
<li><?=$name?></li>
<?php endforeach; ?>
</ul>
Contrast this with the pseudo-code used by a template engine:
<ul>
{foreach from=$addressbook item="name"}
<li>{$name}</li>
{/foreach}
</ul>
Yes, the template engine example is a bit cleaner, but it comes at the
price of performance, as the pseudo-code must be converted back into
PHP to run. Since one of our goals is maximum performance, we opted to
not require the use of a template engine.
A template engine is simply a way to embed your back-end code into your html. This is more common in languages like Python and Ruby than PHP since PHP already supports embedding within html code.
That specific templating engine may be easier for those coming from other back-end languages, particularly Python or Ruby since Django and Rails have very similar-looking syntax for templates.
While not necessarily a "template engine", I typically organize my Codeigniter projects where I have a template.php view that contains the skeleton layout and the content of each page of the site/application is a separate view that is loaded within the template.php file. This way I am not rewriting code on each page.
Template engines are all about personal preference--they aren't needed, but some people feel more comfortable using them if that's what they are used to. And people are more effective the less they have to think about their workflow!
In CodeIgniter Userguide describe that CodeIgniter does come with a simple template parser that can be optionally used, it does not force you to use one.
But if u want to use template, I suggest to use this library that it is very simple.
http://williamsconcepts.com/ci/codeigniter/libraries/template/reference.html
Related
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).
How to make master pages in php? Like a Layout.cshtml (and RenderBody()) in ASP.NET MVC?
Thanks!
P.S. Maybe there's a third-party tool for the purpose?
EDIT
Ok. The thing is not about MVC architecture! Do look here: http://jsfiddle.net/challenger/8qn22/109/
I want the master page/layout to stay when user gets redirected to the other page
Want an average page to be nested inside the content division. So if it is a form I want this form to be displayed like: http://jsfiddle.net/challenger/XgFGb/17/
Here's what PHP standard framework/api supports:
The require("/definitions.php") function loads class, function and constants defines from a file and outputs the content outside of PHP code to php://stdout (on a webserver this is what is sent to the browser). You might wanna use require_once for importing dependencies (php files with definitions).
Use the PHP's open and close tags to obtain something close to templating functionality.
For example a normal page would look like this:
while an included (and repeatably includable) one could look like this:
I'm not saying "don't use templating engines", just showing a clear and simple way of achieving things which PHP is purposely built for. If this is enough for you needs, I then do say "don't use templating engines for the sake of it" (btw, if you are tidy, you can easily separate logic from views, without strict and sometimes cumbersome MVC frameworks).
Off hand, I know that the Laravel framework includes the Blade templating engine. It uses a syntax very similar to Razor.
Example:
#layout('master')
#section('navigation')
#parent
<li>Nav Item 3</li>
#endsection
#section('content')
Welcome to the profile page!
#endsection
(Razor, Blade, loller skates)
In PHP, there is a very similar technique called templating. Instead of a master page, you have a template. The language itself has no built-in templating features, but there are third-party templating engines (Smarty, PHPTAL, and XTemplate, to name a few).
If you want to have "real" master pages, it is entirely possible to implement them. Just wrap you master page into a class and include() that class into your content pages.
Also Zend Framework supports a two step view, where a view template is rendered inside a layout template. I think this satisfies your need for master pages.
See following links:
Approximating Master Pages in PHP
Is there anything like MasterPages on CodeIgniter Framework?
PHP Equivalent of Master page in ASP.NET
ASP.Net MVC or Zend Framework. What is your opinion
http://hoolihan.net/blog-tim/2008/09/24/simple-masterpages-with-php/
The Twig template engine offers Template Inheritance
The most powerful part of Twig is template inheritance. Template inheritance allows you to build a base "skeleton" template that contains all the common elements of your site and defines blocks that child templates can override.
Can be used as a standalone, but was made by the people behind the popular symfony framework.
A while ago (several years), I achieved something like this using Smarty, and extending it to contain a method to the effect of DisplayMaster("NameOfTemplate", "NameOfMasterTemplate")
It works by rendering a template and passing the result into another (master) template.
Above has 2 templates:
NameOfTemplate, just has the main content section, e.g.
<div>...{$someProcessing}</div>
NameOfMasterTemplate has the outer html
<html>...<body><div class="layout">{$innerHtml}</div></body></html>
Ok. The solution that suits me the best is described here http://www.phpro.org/tutorials/Introduction-to-PHP-templating.html#9. It is easy, fast to imlement and doesn't enforce you to use a templating engine. Cool!
Add this piece of code in the content area of your master.php file...
I am using it like this and it perfectly working for me
<li>BLOG</li>
<div class="container content">
<?php
if(isset($_GET['page']))
{
$page_name = $_GET['page'];
include("/".$page_name);
}
?>
</div>
To help with the organisation and structure of my project, I would like to adopt some kind of template technique.
I have looked over quite a few examples, and would like to use only php to convert place holders in the template, to actual content.
The issue I have, is what happens when you wish to loop through information retrieved from a database, or if you only want to display certain things on the page if certain conditions are met (if statements)?
I’m still toying with the idea if this is the way to go, and would consider any views you may have.
Try taking a look at this page, makes for very neat php including (so to say) in html templates.
http://php.net/manual/en/control-structures.alternative-syntax.php
for instance:
<ul>
<?php foreach ($list as $item): ?>
<li><?=$item?></li>
<?php endforeach; ?>
</ul>
if this is not what you mean, please elaborate.
PHP is a template engine itself so in my opinion an additional templating system is redundant. PHP provides all the tools for conditional output, loops, escaping, number formatting, etc and there's no reason to re-create all that.
It does make sense to split your templates into multiple PHP files for re-use. Keep your controller/model in a different file which does all the heavy work and includes the PHP templates. See the MVC pattern for more info.
I wouldn't recommend short tags like <?=$var?> because on most servers that option is disabled.
Hope that helps
What is the best, easiest, and fastest way to use a template for a page. Right now I have been using a function to create my template for each page.
$title = "Kick Me";
<?php pageHtmlHeadStart($title)>
<!-- Were Javascript would go -->
<?php pageHtmlHeadEnd(); guiHeader(); ?>
Content went here.
<?php guiFooter; ?>
I uses to use includes...
<?php include('header.php'); ?>
Content went here.
<?php include('footer.php') ?>
I was thinking about using PHP Object to do the same thing too. It would run like the functions way of doing it. I would create a GUI class that would have the template wrapper and include some scripts to display content (via echo) that I use a few time over again on different page.
I probably will answer my own questions when say this... I like the current way do it with the functions. I just don't know if this is bad coding habits.
In the context of templates, there is nothing wrong to use include() statements. They make clean looking code and makes it easy to share html snippets between templates.
Whether to use instance methods, static methods or functions for "template tags" depends on the architecture of your framework or application. While generally OOP is really good thing, making everything an object doesn't magically make your code better.
PHP itself does make a good template language. There is no need to invent another "language" for templates – neither is it wrong, as long as you cache your parsed files (like Smarty does).
You may want to check out Savant and Smarty template engines. I also recommend you to study various PHP MVC frameworks and see how things are implemented there: Symfony, Kohana.
If you want a template, then use a templating language. Using PHP for templating is definitely not a good practice according to me.
I am creating a site in which different pages can look very different depending upon certain conditions (ie logged in or not, form filled out or not, etc). This makes it necessary to output diferent blocks of html at different times.
Doing that, however, makes my php code look horrific... it really messes with the formatting and "shape" of the code. How should I get around this? Including custom "html dump" functions at the bottom of my scripts? The same thing, but with includes? Heredocs (don't look too good)?
Thanks!
Don't panic, every fresh Web programmer face this problem.
You HAVE TO separate your program logic from your display. First, try to make your own solution using two files for each Web page :
one with only PHP code (no HTML) that fills variables
another with HTML and very few PHP : this is your page design
Then include where / when you need it. E.G :
myPageLogic.php
<?php
// pure PHP code, no HTML
$name = htmlspecialchars($_GET['name']);
$age = date('Y') - htmlspecialchars($_GET['age']);
?>
myPageView.php
// very few php code
// just enought to print variables
// and some if / else, or foreach to manage the data stream
<h1>Hello, <?php $name ?> !</h1>
<p>So your are <?php $age?>, hu ?</p>
(You may want to use the alternative PHP syntax for this one. But don't try to hard to make it perfect the first time, really.)
myPage.php
<?php
require('myPageLogic.php');
require('myPageView.php');
?>
Don't bother about performance issues for now. This is not your priority as a newbie. This solution is imperfect, but will help you to solve the problem with your programming level and will teach you the basics.
Then, once your are comfortable with this concept, buy a book about the MVC pattern (or look for stack overflow entries about it). That what you want to do the NEXT TIME. Then you'll try some templating systems and frameworks, but LATER. For now, just code and learn from the beginning. You can perfectly code a project like that, as a rookie, it's fine.
Use a mvc approach.
http://www.phpmvc.net/
This is not something that you will pick up in a couple of hours. You really need to practice it. Main thing is the controller will access your model (the db layer), do stuff to your data and then send it to the view for rendering. This is oversimplified but you just need to read and practice it to understand it.
This is something I used to help me learn it.
http://www.onlamp.com/pub/a/php/2005/09/15/mvc_intro.html
Try to separate your content and layout from your code as much as possible. Any time you write any HTML in a .php file, stop and think "Does this really belong here?"
One solution is to use templates. Look at the Smarty templating system for a pretty easy-to-use option.
Doing that, however, makes my php code look horrific... it really messes with the formatting and "shape" of the code. How should I get around this?
Treat your PHP and HTML as a single hierarchy, with a single, consistent indentation structure. So a PHP enclosing-structure such as an 'if' or 'for' introduces a new level of indentation, and its contents are always a balanced set of start and end-tags. Essentially you are making your PHP 'well-formed' in the XML sense of the term, whether or not you are actually using XHTML.
Example:
<div class="prettybox">
Hello <?php echo(htmlspecialchars($name)) ?>!
Your food:
<?php foreach($foods as $food) { ?>
<a href="/food.php?food=<?php echo(urlencode($food)) ?>">
<?php echo(htmlspecialchars($food)) ?>
</a>
<?php } ?>
<?php if (count($foods)==0) { ?>
(no food today)
<?php } ?>
</div>
Be wary of the religious dogma around separating logic and markup rearing its head in the answers here again. Whilst certainly you want to keep your business-logic out of your page output code, this doesn't necessarily mean a load of overhead from using separate files, classes, templates and frameworks is really necessary for what you're doing. For a simple application, it is likely to be enough just to put the action/logic stuff at the top of the file and the page output below.
(For example from one of the comments above, doing htmlspecialchars() is page-output functionality you definitely don't want to put in the action bit of your PHP, mixed up in all the business logic. Always keep text as plain, unescaped strings until the point where it leaves your application logic. If typing 'echo(htmlspecialchars(...))' all the time is too wordy, you can always make a function with a short name like 'h' that does the same.)
From the sound of your problem, it seems you might not have much separation between logic and presentation in your code. When designing an application this is a very important consideration, for reasons exactly demonstrated by the situation your currently facing.
If you haven't already I'd take a look at some PHP templating engines such as Smarty.
In cases like that I write everything incrementally into a variable or sometimes an array and then echo the variable/array. It has the added advantage that the page always renders in one go, rather than progressively.
What I end up doing in this situation is building 'template' files of HTML data that I Include, and then parse through with regular expressions. It keeps the code clean, and makes it easier to hand pieces off to a designer, or other HTML person.
Check out the ideals behind MVC programming practices at Wikipedia
You need a framework. This will not only make your code pretty (because of the already-mentioned model-view-controller pattern, MVC) - it will save you time because of the components that are already written for it.
I recommend QCodo, it's amazing; there are others - CakePHP, Symfony.
If it's a big project a framework might be in order. If not, create some template files and at the top of the page decide which template file to include.
for example
if ($_SESSION['logged_in'])
include(TPL_DIR . 'main_logged_in.tpl');
else
include(tPL_DIR . 'main.tpl');
just a simple example
as mentioned above.. you are fixing the symptom, not the problem..
What you need is the separation of logic and presentation. Which can be done with some sort of mvc framework. Even if you don't want to go all the way with a mvc framework.. A templating engine is a must at least if your logic is complicated enough that you have trouble with what you are explaining
I strongly suggest savant instead of smarty,
you don't have to learn a new templating "language" in order to create templates, savant templates are written in php
if you don't want to use php you can define your own template "language" with a compiler
it's easily extendable by your own php objects
Separating logic from presentation does not mean that all you business logic has to be in php and your presentation logic in something else, the separation is a conceptual thing, you hae to separate the logic that prepares data form the one that shows it. Obviously the business logic does not have to contain presentation elements.
In stead of implementing templating systems on top of a templating system (PHP itself), creating overhead per default, you can go for a more robust solution like XSL Transformations, which also complies with the MVC princples (provided you seperate your data-retrieval; plus, I personally split the logic from displaying the XML with different files).
Imagine having the following information in an array, which you want to display in a table.
Array
{
[car] => green
[bike] => red
}
You easily create a script that outputs this information in XML:
echo "<VEHICLES>\n";
foreach(array_keys($aVehicles) as $sVehicle)
echo "\t<VEHICLE>".$sVehicle."</NAME><COLOR>".$aVehicles[$sVehicle]."</COLOR></VEHICLE>\n";
echo "</VEHICLES>\n";
Resulting in the following XML:
<VEHICLES>
<VEHICLE>
<NAME>car</NAME>
<COLOR>green</COLOR>
</VEHICLE>
<VEHICLE>
<NAME>bike</NAME>
<COLOR>red</COLOR>
</VEHICLE>
</VEHICLES>
Now this is all excellent, but that won't display in a nice format. This is where XSLT comes in. With some simple code, you can transform this into a table:
<xsl:template match="VEHICLES">
<TABLE>
<xsl:apply-templates select="VEHICLE">
</TABLE>
</xsl:template>
<xsl:template match="VEHICLE">
<TR>
<TD><xsl:value-of select="NAME"></TD>
<TD><xsl:value-of select="COLOR"></TD>
</TR>
</xsl:template>
Et voila, you have:
<TABLE>
<TR>
<TD>car</TD>
<TD>green</TD>
</TR>
<TR>
<TD>bike</TD>
<TD>red</TD>
</TR>
</TABLE>
Now for this simple example, this is a bit of overkill; but for complex structures in big projects, this is an absolute way to keep your scripting logic away from your markup.
Check this question about separating PHP and HTML, there are various ways to do it, including self written templating systems, templating systems such as Smarty, PHP as a templating system on it's own, etc etc etc...
I think you've two options here, either use a MVC Framework or use the lazy templating way which would put significant overhead on your code. Obviously I'm with the former, I think learning MVC is one of the best web development tricks in the book.