I am trying to work with FatFree framework and trying to use the template engine. I render the template with the following code -
echo Template::serve('template.php');
The problem which I'm facing is that, inside the template.php file the F3 tags are recognised but any PHP code doesn't work. For instance, if I have the following code in the template.php file -
<?php
if (F3::get('var') == 'var1') {
?>
<span>var1 is present</span>
<?php
} else {
?>
<span>var1 not present</span>
<?php
}
?>
Here both var1 is present and var1 not present is printed irrespective of the value of var. Also, php for loops are not working - so basically all the php code is not working.
However, if I used <F3:check> to write the above PHP code, then everything works fine. Can we not use PHP code in templates. If this is the case, this is a serious limitation.
I have found the answer, although I don't really like it.
There is two different functions, F3::render() and Template::serve()
With F3::render() you can evaluate PHP expressions and use the F3::get() to retrieve variables. According to the website: "The only issue with embedding PHP code in your templates is the conscious effort needed to stick to MVC principles"
The Template::serve() is for templating only. Meaning its simply to process the templating language.
So basically, and yes it sucks and doesn't make sense, you can evaluate PHP code in the F3::render() and you can't use templating variables ({{#var}}) -OR- you can use Template::serve() and you are limited to only calling PHP functions, and not truly evaluating PHP code.
Maybe try to use different template engine which will allow you define easier the blocks variable dependency?
For example in PHPTal http://phptal.org/manual/en/split/tal-condition.html you can do it like that:
<div tal:condition="php: var == 'var1'">
....
</div>
It is undocumented but you can put code within {~ ~} in a template and it will be converted to <?php ?> when the template is compiled (using v3.6).
e.g. {~ #color = 'red' ~} will become <?php $color = 'red' ?>
Related
I have been designing websites for a while now, but there is one thing that I have never been quite sure of when using PHP and HTML. Is it better to have the whole document in PHP and echo HTML like so:
<?php
doSomething();
echo "<div id=\"some_div\">Content</div>";
?>
Or have a HTML file like so and just add in the PHP:
<html>
<body>
<?php doSomething(); ?>
<div id="some_div">Content</div>
</body>
</html>
It seems tidier to echo HTML, especially if lots of PHP gets used throughout the page, but doing so loses all formatting of the HTML i.e. colors in the IDE etc.
There are varying opinions on this. I think there are two good ways:
Use a templating engine like Smarty that completely separates code and presentation.
Use your second example, but when mixing PHP into HTML, only output variables. Do all the code logic in one block before outputting anything, or a separate file. Like so:
<?php $content = doSomething();
// complex calculations
?>
<html>
<body>
<?php echo $content; ?>
<div id="some_div">Content</div>
</body>
</html>
Most full-fledged application frameworks bring their own styles of doing this; in that case, it's usually best to follow the style provided.
I think this would depend on your group's or your own decided convention. And it can and should vary depending on what type of file you're working in. If you follow the MVC pattern then your views should be the latter. If you're writing a class or some non-output script/code then you should use the former.
Try to keep a separation of display or formatting of output and the logic that provides the data. For instance let's say you need to make a quick page that runs a simple query and outputs some data. In this case (where there is no other existing infrastructure or framework) you could place the logic in an include or in the top or the bottom of the file. Example:
<?php
# define some functions here that provide data in a raw format
?>
<html>
<body>
<?php foreach($foo = data_function($some_parameter) as $key => $value): ?>
<p>
<?=$value;?>
</p>
<?php endforeach; ?>
</body>
</html>
Or you could place the logic and function definitions in an include file or at the bottom of the file.
Now if you're producing some sort of class that has output (it really shouldn't) then you would echo the HTML or return it from the method being called. Preferably return it so that it can be output whenever and however the implementer would like.
The syntax highlighting is an important benefit of the second method, as you said. But also, if you're following good practices where logic and presentation are separated, you will naturally find that your files that contain HTML are almost entirely HTML, which then, naturally, leads to your second method again. This is the standard for MVC frameworks and the like. You'll have a bunch of files that are all PHP, doing logic, and then when that's done they'll include a presentation file which is mostly HTML with a sprinkling of PHP.
Simple:
More PHP - close HTML in PHP. When you generate HTML code in PHP, when you are doing something like a class, so it is better to make it in echo.
Less PHP - close PHP in HTML. This is stuff like just putting vars into fields of HTML stuff, like forms... And such.
The best approach is to separate the HTML from the PHP using template system or at least some kind of HTML skeleton like:
<main>
<header/>
<top-nav/>
<left-col>
<body />
</left-col>
<right-col />
<footer/>
</main>
Each node represents a template file e.g. main.php, hrader.php and so on. Than you have to separate the PHP code from the templates as something like functions.php and fineally use your second approach for template files and keeping functions clean of "echos" and HTML.
If you can, use a template engine instead.
Although it is slightly easier at first to mix your HTML and PHP, separating them makes things much easier to maintain later on.
I would recommend checking out TemplateLite which is based on Smarty but is a little more light weight.
I've reached a conclusion that using views in MVC framework e.g. Laravel, Yii, CodeIgniter is the best approach even if you are not displaying the html straight away.
Inside the view do all the echoing and looping of prepared variables, don't create or call functions there, unless formatting existing data e.g. date to specific format date('Y-m-d', strtodate(123456789)). It should be used only for creating HTML, not processing it. That's what frameworks have controllers for.
If using plain PHP, create you own view function to pass 3 variables to - html file, array of variables, and if you want to get output as string or print it straight away for the browser. I don't find a need for it as using frameworks is pretty much a standard. (I might improve the answer in the future by creating the function to get view generated HTML) Please see added edit below as a sample.
Frameworks allow you to get the HTML of the view instead of displaying it. So if you need to generate separate tables or other elements, pass the variables to a view, and return HTML.
Different fremeworks may use various type of templating languages e.g. blade. They help formatting the data, and essentially make templates easier to work with. It's also not necessary to use them for displaying data, or if forced to use it by the framework, just do required processing before posting the variables, and just "print" it using something like {{ yourVariable }} or {{ yourVariable.someProperty }}
Edit: here's a plain PHP (not framework PHP) - simple-php-view repository as a sample view library that allows to generate HTML using variables. Could be suitable for school/university projects or such where frameworks may not be allowed.
The repository allows to generate HTML at any time by calling a function and passing required variables to it, similar to frameworks. Separately generated HTML can then be combined by another view.
It depends on the context. If you are outputting a lot of HTML with attributes, you're going to get sick of escaping the quotation marks in PHP strings. However, there is no need to use ?><p><? instead of echo "<p>"; either. It's really just a matter of personal taste.
The second method is what I usually use. And it was the default method for me too. It is just to handy to get php to work inside html rather than echo out the html code. But I had to modify the httpd.conf file as my server just commented out the php code.
I am building my website completely in PHP. I am trying to make it as much flexible as possible.
I have seen there are some softwares made in PHP that are able to get a HTML page, and before showing it, the PHP code recognizes the code inside brackets {PHP Code} as PHP code, runs it and only then shows the final page.
<h1>Hi My Name is {echo $name}</h1>
How can I achieve the same? I know there is Smarty Code. But I do not want to learn Smarty, I just want to know how to check a HTML page with PHP, find every bracket and threat that as PHP before showing the page..?
Can you point me somewhere?
Are you looking for PHP's basic syntax?
If you enable short_open_tags (it usually is enabled by default), this will work:
<h1>Hi My Name is <?=$name?></h1>
otherwise, this will always work:
<h1>Hi My Name is <?php echo $name; ?></h1>
PHP is already a templating language - there often is no need to add another layer of templating on top of it.
I want to keep the template files separated from the php engine
In fact, you don't
Your template files would behave as native PHP files in every way.
So, there is asolutely no [logical] reason to prefer such a strange solution over native PHP.
use the php tags for the echo statement.
<h1>Hi my name is <?php echo $name; ?></h1>
Well, just point apache to index.php which includes phtml templates into itself. Use <?php ?> instead of { }.
I don't want to use an MVC framework. I don't want to use a template engine. I am a few man shop where the developers where all the hats, no graphic artists. We do it all (all layers). I do not want code mixed with presentation, like I have with Classic ASP.
But, I do not know what my code is suppose to look like between server side and the actual presentation.
If I'm not emitting HTML in my server side code, how does it get to the HTML page so I can do things like <span><?= $myvar ?></span>? and put loops in the html page?
Thank you for any advice.
For using loops and all, I use the alternative syntax for the control structures.
An example:
<div id="messages"<?php if(!(isset($messages) && count($messages))): ?> class="hidden"<?php endif; ?>>
<?php if(isset($messages)): ?>
<?php foreach($messages as $message): ?>
<div class="message"><?php echo $message; ?></div>
<?php endforeach; ?>
<?php endif; ?>
</div>
For more information, see this: http://php.net/manual/en/control-structures.alternative-syntax.php
Oh also, I use a semi-MVC structure, where I have a class that handles templates (views), basically it's just a class that I create an instance of, pass a set of variables, then render the template when the instance get destroyed. I have an array of variables in that class, and then use extract to pass all variables in the include, like so:
extract($this->variables, EXTR_SKIP);
include($this->file);
EDIT: Here is the same example in Smarty:
<div id="messages"{if isset($messages) && !count($messages)} class="hidden"{/if}>
{if isset($messages)}
{foreach from=$messages item=message}
<div class="message">{$message}</div>
{/foreach}
{/if}
</div>
Simple PHP projects usually generate the full HTML in-place instead of populating templates, so you'd just echo it out in your PHP code.
This gets messy, so you WILL end up coding some kind of templating system for any moderately complex website.
A possible alternative is to serve your page as completely static HTML/CSS and use AJAX to fetch the actual contents dynamically (JSON would be a good transport format, it's native to JS and can easily be generated from PHP). This gets you rid of all the HTML littered across your PHP code. Whether this is a viable alternative or not depends on the case.
<span><?= $myvar ?></span> works.
A loop would look like:
<html>
<body>
<?php
for ($i=1; $i<=5; $i++)
{
echo "The number is " . $i . "<br />";
}
?>
</body>
</html>
Example taken from here.
I really recommend that you use the php Template Inheritance system. (Don't let it scare you, it's only one file.) This is a simple set of functions that helps you to build extensible PHP views without the problems and limitations of manual includes.
It's still Pure PHP, so you don't need to learn some strange template language. It may not look like much, but it's really powerful once you start using it.
To be sure, you can do it all by yourself - but what you want is still MVC pattern, or separation of concerns ("I do not want code mixed with presentation"). Or at least MV, for very simple applications (although it's still dirty, having models directly influence the view).
The easiest way to achieve this is to first collect and process all data, then just print them. No complex code allowed in the php files directly exposed to the web.
<?php
require('model.inc');
process_capuchin_monkey_order_form();
?>
...
<h1>Thank you for your order of <?php echo $order->num_monkeys; ?> monkeys.</h1>
...
typically you would want to just make sure you have as little PHP in your HTML as possible. This means doing all of the data processing before hand, and simply passing a set of variables in one way or another to a method or function that includes the HTML.
Any HTML with PHP intermixed could be considered a template. Here's a simplified example:
// view class
class View {
public function render($html_template) {
include('view_path/' . $html_template . '.php');
}
}
// html template file 'view_path/main.php'
<html>
<body>
<h1><?= $this->title ?></h1>
</body>
</html>
// usage
$view = new View();
$view->title = 'Some Title';
$view->render('main');
You should use an MVC-like separation of concerns no matter what you do. This means:
At least one file is all html and is given a handful of variables. (view/template)
At least one file is all php and only talks to the database. (model)
At least one file processes the http request, pulls data from database, and executes the view.
The core of every php templating language is the use of extract() and include inside a function:
function render_template($___filename, $___data) {
extract($___data, EXTR_SKIP);
include $__filename;
}
You can pretty this up with a class interface (view objects) or with output buffering, but this is the core of every template system. Your controller's responsibility is simply to assemble that $__data argument (usually with data from a database) for a given view.
I am just wondering if its normal to embed PHP in the HTML, or is it considered dirty/unprofessional. For example consider following lines:
<? if($photo == 0) { ?>
<div class ="reminder">Hey <?=$name;?>, You don't have any photo. </div>
<? } else { ?>
<div class ="ok">Do you want to change your photo? </div>
<? } ?>
Is this kind of code ok? How the similar work can be done in a clean/professional way (without PHP frameworks? )
Thanks.
As long as you keep the logic of your program outside the html, it is ok. You need to mix it in your templates, for example. Template-engines like smarty replace the {$myVar} with < ? php echo $myVar; ? > (simply spoken), so it is not possible to avoid it completely. But things like
<?php
include "db.php";
connect_db();
// check login
echo "< html >< head><body>...";
?>
is NOT good practice, because you mix everything together: program logic (login-check, db-stuff) and output (echo html). Just have a look at the MVC and keep the "separation of concerns" in mind.
Your example looks ok because you have only that logic in your html which is needed to control the output directly. But calculating the value of $photo, depending on a db entry for example, would NOT be good in your html, because this is program logic. Output (HTML) and logic should be devided all the time.
It's very normal, whether it's good or not is a completely separate topic. It's really all about the size of your project and your requirements for maintainability/flexibility.
If it's a small project, just do what you have to in order to get it done. However a point exists at which it becomes unwieldy to develop without a framework. This is all very subjective and varies from project to project, but this is the general principle.
It's OK to use PHP in templates but many people prefer to work with a templating language because it forces separation and ensures you don't litter your templatse with loads of PHP. If you do go down the template route Twig and Smarty are quite good since they compile the template into PHP which speeds things up.
If you're writing PHP in your templates try to follow some best practise coding standards to keep things neat. For example:
Use full <?php tags for compatibility.
When writing any loops instead of curly braces use colons. To end the statement you need to explicitly write it as endforeach/endif/endwhile/etc. This makes PHP templates more readable.
If you have a lot of logic move this into an external PHP file to keep the PHP in your template short and readable
If there is only one PHP statement in your PHP tag you don't need to end it with a semi-colon. Again, helps readability
An example:
<?php if ($photo == 0): ?>
<div class ="reminder">Hey <?php echo $name ?>, You don't have any photo.</div>
<?php else: ?>
<div class ="ok">Do you want to change your photo?</div>
<?php endif ?>
See more at:
http://www.php.net/manual/en/control-structures.alternative-syntax.php
http://framework.zend.com/manual/en/coding-standard.overview.html
for that you can use smarty templete .... it improves your coding style and works fast ... visit smarty and try it, it's really awesome
From what I have read either will work, but most people just use the echo statements for small, conditional html.
I try to keep this at a minimum, because i find it harder to debug it with all the
< ? } ?>
flowing around in the code (wordpress theme gurus does this alot)
There will be many opinions about this. Mixing HTML and PHP can become very messy, but this looks fine. Many professionals work just this way. If it works for you, it's good.
To make it more readable, I tend to keep the brackets on separate lines, just so you can be sure to be able to find them all easily, but thats just me.
there was an answer from guy named alexn
Dunno why did he delete it, it's looks best answer to me, so, I am only reproducing it:
I would say that's the way to go. You
have a nice, clean separation of PHP
and HTML.
Here's another option:
<? if($photo == 0): ?>
<div class ="reminder">Hey <?=$name?>, You don't have any photo. </div>
<? else: ?>
<div class ="ok">Do you want to change your photo? </div>
<? endif ?>
I have been designing websites for a while now, but there is one thing that I have never been quite sure of when using PHP and HTML. Is it better to have the whole document in PHP and echo HTML like so:
<?php
doSomething();
echo "<div id=\"some_div\">Content</div>";
?>
Or have a HTML file like so and just add in the PHP:
<html>
<body>
<?php doSomething(); ?>
<div id="some_div">Content</div>
</body>
</html>
It seems tidier to echo HTML, especially if lots of PHP gets used throughout the page, but doing so loses all formatting of the HTML i.e. colors in the IDE etc.
There are varying opinions on this. I think there are two good ways:
Use a templating engine like Smarty that completely separates code and presentation.
Use your second example, but when mixing PHP into HTML, only output variables. Do all the code logic in one block before outputting anything, or a separate file. Like so:
<?php $content = doSomething();
// complex calculations
?>
<html>
<body>
<?php echo $content; ?>
<div id="some_div">Content</div>
</body>
</html>
Most full-fledged application frameworks bring their own styles of doing this; in that case, it's usually best to follow the style provided.
I think this would depend on your group's or your own decided convention. And it can and should vary depending on what type of file you're working in. If you follow the MVC pattern then your views should be the latter. If you're writing a class or some non-output script/code then you should use the former.
Try to keep a separation of display or formatting of output and the logic that provides the data. For instance let's say you need to make a quick page that runs a simple query and outputs some data. In this case (where there is no other existing infrastructure or framework) you could place the logic in an include or in the top or the bottom of the file. Example:
<?php
# define some functions here that provide data in a raw format
?>
<html>
<body>
<?php foreach($foo = data_function($some_parameter) as $key => $value): ?>
<p>
<?=$value;?>
</p>
<?php endforeach; ?>
</body>
</html>
Or you could place the logic and function definitions in an include file or at the bottom of the file.
Now if you're producing some sort of class that has output (it really shouldn't) then you would echo the HTML or return it from the method being called. Preferably return it so that it can be output whenever and however the implementer would like.
The syntax highlighting is an important benefit of the second method, as you said. But also, if you're following good practices where logic and presentation are separated, you will naturally find that your files that contain HTML are almost entirely HTML, which then, naturally, leads to your second method again. This is the standard for MVC frameworks and the like. You'll have a bunch of files that are all PHP, doing logic, and then when that's done they'll include a presentation file which is mostly HTML with a sprinkling of PHP.
Simple:
More PHP - close HTML in PHP. When you generate HTML code in PHP, when you are doing something like a class, so it is better to make it in echo.
Less PHP - close PHP in HTML. This is stuff like just putting vars into fields of HTML stuff, like forms... And such.
The best approach is to separate the HTML from the PHP using template system or at least some kind of HTML skeleton like:
<main>
<header/>
<top-nav/>
<left-col>
<body />
</left-col>
<right-col />
<footer/>
</main>
Each node represents a template file e.g. main.php, hrader.php and so on. Than you have to separate the PHP code from the templates as something like functions.php and fineally use your second approach for template files and keeping functions clean of "echos" and HTML.
If you can, use a template engine instead.
Although it is slightly easier at first to mix your HTML and PHP, separating them makes things much easier to maintain later on.
I would recommend checking out TemplateLite which is based on Smarty but is a little more light weight.
I've reached a conclusion that using views in MVC framework e.g. Laravel, Yii, CodeIgniter is the best approach even if you are not displaying the html straight away.
Inside the view do all the echoing and looping of prepared variables, don't create or call functions there, unless formatting existing data e.g. date to specific format date('Y-m-d', strtodate(123456789)). It should be used only for creating HTML, not processing it. That's what frameworks have controllers for.
If using plain PHP, create you own view function to pass 3 variables to - html file, array of variables, and if you want to get output as string or print it straight away for the browser. I don't find a need for it as using frameworks is pretty much a standard. (I might improve the answer in the future by creating the function to get view generated HTML) Please see added edit below as a sample.
Frameworks allow you to get the HTML of the view instead of displaying it. So if you need to generate separate tables or other elements, pass the variables to a view, and return HTML.
Different fremeworks may use various type of templating languages e.g. blade. They help formatting the data, and essentially make templates easier to work with. It's also not necessary to use them for displaying data, or if forced to use it by the framework, just do required processing before posting the variables, and just "print" it using something like {{ yourVariable }} or {{ yourVariable.someProperty }}
Edit: here's a plain PHP (not framework PHP) - simple-php-view repository as a sample view library that allows to generate HTML using variables. Could be suitable for school/university projects or such where frameworks may not be allowed.
The repository allows to generate HTML at any time by calling a function and passing required variables to it, similar to frameworks. Separately generated HTML can then be combined by another view.
It depends on the context. If you are outputting a lot of HTML with attributes, you're going to get sick of escaping the quotation marks in PHP strings. However, there is no need to use ?><p><? instead of echo "<p>"; either. It's really just a matter of personal taste.
The second method is what I usually use. And it was the default method for me too. It is just to handy to get php to work inside html rather than echo out the html code. But I had to modify the httpd.conf file as my server just commented out the php code.