Blade template vs plain php in Laravel - php

As I understand, Blade is simply regex parser, which will translate any Blade construction into PHP code, and then generate plain HTML from that PHP. Seems like this process makes loading files with Blade templates slower (because of the extra step Blade -> PHP). If so, why do I want to use Blade at all? Just because of the elegant syntax or because Blade files are stored in cache?

You'd use Blade because you want to use Blade. Like you've said it has a much nicer syntax and once you know its simple syntax it's very quick to use.
Regular PHP:
<?php if ($user->isLogged()): ?>
Welcome back, <strong><?= $user->name; ?></strong>
<?php endif; ?>
Blade:
#if ($user->isLogged())
Welcome back, <strong>{{ $user->name }}</strong>
#endif
Of course that's just a basic control structure. Blade has built in templating support as well.
Speed
There should be virtually no speed difference between the two as on the first load Laravel will compile any views that have changed into their PHP equivalent. Subsequent page loads will use this compiled file instead (they are stored at app/storage/views).
I guess the only extra overhead would be the initial check to see if the view has been compiled yet. Bugger all though.

Related

How to replace <?php echo with curly brace({{ }})

I want to cleanup my php file. I really like the way how blade template use curly brace to display php variables {{ $user }} https://laravel.com/docs/5.8/blade#displaying-data
Is there a way to use a functionality like that without using blade template. Using <?php echo $user ?> get's very repetitive.
This is not possible in PHP without using a template engine because it is a different syntax. Anyway in my opinion sometimes it is not the best idea to use a template engine because PHP is already kind of a template engine.
All what you seem to care about is the short syntax of echoing a variable in blade:
{{ user }}
This is as short as the syntax the PHP template engine itself provides:
<?= $user ?>
Of course Laravel (and similar) has a good reason to use template engine like blade - in order to seperate controller, logic and view (such that the view can be made by non-programmer designers for instance).
Update (thx to comments): The codes provided above do not exactly do the same as template engines (as an additional layer) may take care of e.g. escaping variables, which adds safety to the code.
As the OPs' code has already been built with echo and he is just searching for a replacement I did not mention this, but its a notable difference that you have to take care of some things yourself if not using one.

Laravel Blade comment before "#if"

Sometimes, in HTML, I need to avoid adding extra white space, but I also need to add "#if()" blocks. In order to accomplish this, I've taken this approach:
some text{--
--}#if($someCondition){--
--}more text with no space between
#endif
And this approach has been working great. However, after upgrading my development and live environments to Laravel 5.5 (from Laravel 5.2) the Development environment works fine, but the live environment renders the above blade into the following HTML:
some text#if($someCondition)more text with no space between
<?php endif; ?>
... So the "if" statement immediately after the blade comment is left as plain text.
I know that it's possible, because both my development environments render the page correctly. I've looked at PHP versions and copied over the entire code directory, but I cannot find any difference between them at all, let alone a difference that would cause this to be processed differently.
Is there any reason why Laravel's blade engine wouldn't allow a "#" right after blade comment?
Using PHP 7.029, Laravel 5.5, CentOS.
I've discovered the issue. The view was cached on the development environments, which is why it was working.
It looks like there was a new bug introduced in Laravel somewhere between 5.3 and 5.5. The blade comments are being removed before the rest of the blade is analysed, which can cause issues as I showed in the question here. This was working previously in Laravel 5.2.
I did find a work around:
some text{{null
}}#if($someCondition){--
--}more text with no space between
#endif
Produces something that works:
some text<?php echo e(null); ?><?php if($someCondition): ?>more text with no space between
<?php endif; ?>
An alternative way to solve the original issue would be to directly write some PHP code for your if statements:
some text<?php
if($someCondition):
?>more text with no space between<?php
endif;
?>
(however, I agree this is not the sweatest way to write templates, as you will have a mix between Blade and PHP)
Laravel converts your blade templates into PHP, then use these converted files for rendering. So if you write directly some PHP code with your Blade templates, it will just work the same.
Could always use the Blade native php enclosures...
some text{{ if(condition) {do something} }}more text
This gives the the flexibility of inline php with your HTML.

If conditions performances in Blade templates in Laravel

I've just a simple questions about performances using blade templating inside Laravel framework. Let's talk about big size projects.
I'm interested to know if it's more performant-wise to implement the if conditions like this:
#if(isset($training))
<a class="btn" href="{{MYLIB\URL::training_url($sector, $category, $training)}}">Nu inschrijven<span class="icon-right"></span></a>
#endif
or like this?
<?php if (isset($page)){ ?>
<h2>{{{ $page->title }}}</h2>
<?php } ?>
Thanks in advance
Blade syntax compiles to raw PHP. That means this:
#if(isset($page))
<h2>{{{ $page->title }}}</h2>
#endif
Becomes this:
<?php if(isset($page)): ?>
<h2><?php echo e($page->title); ?></h2>
<?php endif; ?>
This compiled template is then stored in storage/framework/views (app/storage/views in Laravel 4)
Conclusion
The only performance hit you get is the compiling. This ideally will only happen when the view file changes or is accessed the first time. If you ask me you surely have other performance bottlenecks to worry about first. (Especially things like database queries or just bad architecture)
Laravel simply converts the blade syntax to a normal php syntax inside temporary view files on the first pass, which are stored in /app/storage.
So there is basically no performance difference between blade and regular php commands
As laravel compiles and caches templates anyway, the only slight overhead is on the very first access to the blade template, and after that there would be no difference in performance at all

Is there a template system like Twig that uses PHP syntax?

I would like to use a template system like Twig (specifically the block functionality) but in plain PHP.
For example, I found http://phpsavant.com/docs/ but it seems that doesn't support blocks or anything similar.
Edit
I found something that appears to have block syntax with regular PHP code: http://phpti.com/
The templating language you are looking for is called PHP!
There is one included in the Laravel framework called Blade.
You can mix plain old PHP with the Blade templating syntax, where {{...}} also translates to <?=...?> or <?php echo ... ?>
Also has blocks you know in Twig, but they are called sections.
#section('heading')
{{ strtoupper("I'm not shouting") }}
#show
<?= strtolower('Shhh!'); ?>
This is under the Illuminate\View namespace - See on GitHub, and can be downloaded with Composer as it is also registered on Packagist - just at the following to your project's composer.json.
{
"require": {
"illuminate/view": "4.*"
}
}
I'm not certain at this point about how you'd attempt to render a template from a custom project. If I find out, I'll update my answer.
Symfony (which uses Twig by default) also has a php-based template system that works very much like Twig. It has template inheritance and uses 'slots', which are equivalent to Twig's blocks. It's a stand-alone library that can be used outside of the full Symfony framework.
http://symfony.com/doc/2.0/cookbook/templating/PHP.html
PHP is a templating language(yes it is) , blocks can be implemented with buffers :
<?php
ob_start();
?>
this the content of the block for <?= date("Y-m-d") ?>
<?php
$content = ob_get_clean();
then in the main layout echo the content of the blocks :
echo $head;
echo $content ;
// ....
in fact that is what most template engines are using.
using template libs have huge advantages though ( caching , escaping by default ,etc ... )
As far as I understand use off Blade for views is optional in Laravel. You can use file name like view.php instead of view.blade.php and use plain old PHP syntax there. Only catch is you cannot have both view.php and view.blade.php as they both respond to
return View::make('view);

What is the best practice to use when using PHP and HTML?

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.

Categories