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
Related
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.
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.
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.
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 am deciding if to use some template engine in php code or no.
Now I take close look to Smarty.
To be honest, it is not clear for me its benefits.
My impressions are not very good from the very beginning.
I tried to go through the demo application: http://www.smarty.net/sampleapp1. And from the very beginning I obtained notices . I fixed this by passing values to forms.
I changes the code from
// adding a guestbook entry
$guestbook->displayForm();
to
// adding a guestbook entry
$guestbook->displayForm(array('Name' => '', 'Comment' => ''));
While guessing this I understand that it complicates debugging the code.
And this also makes me to learn one more language - it is easy, but most easy is not to learn something new at all if there is no needed.
Alternative is to use PHP itself.
Syntax comparison http://www.smarty.net/syntax_comparison is most funny for me: calculate number of symbols.... But I am familiar with PHP and this is easy for me to write on it, and Smarty is new for me. And I don't think that for Web Designers are so difficult to learn some simple php constructs, and Smarty is so simpler in this respect. If I am wrong it would be good to hear web designer here.
Smarty parses the code and this is in fact time overhead.
But at the same time many people use it. And that is why I would like to understand the reasons for this?
Where are the benefits? Am I missing something?
If you know good alternative to Smarty, it would be good to know about.
Thanks!
UPDATE:
I have found also the question on subject: How to use Smarty better with PHP?. In general it is also about not to use Smarty. But this is 1.5 years old. Possibly something changed?
I agree that it causes overhead, I worked in a project that used Smarty and it was a nightmare. The two benefits you can get are
1: designers that are not familiar with PHP can work out with your HTML without coding skills required. But doesn't that mean they will eventually need to study Smarty first? I really don't see any point.
2: For template separation: you can use PHP alternative syntax the same way you would use Smarty, without losing the power of that giant programming language. Example of alternative syntax:
<div>Product list</div>
<?php foreach($products as $product): ?>
<div>Product: <?php echo $product->name; ?> </div>
<div>Price: <?php echo $product->price; ?> </div>
<?php if($product->discountPercentage): ?>
<div>
Discount: <?php echo $product->price * $product->discountPercentage / 100; ?> off! </div>
<?php endif; ?>
<?php endforeach; ?>
I use it in a production environment, and I would say: Not Very Many.
If you're concerned with the look of your code (not an unimportant concern), smarty can make things look a little bit cleaner:
<?php echo $some_var; ?>
vs.:
{$some_var}
this can make your template files much more readable.
It also enforces a stricter separation between your controller and view logic. (since you have to make sure to pass all the relevant variables into the smarty object)
The syntax is straight-forward enough (more so for later versions), so that's not much of a problem.
It can complicate debugging, if only because it is a magical separation layer between your control and view, but in a perfect world you would be verifying each separately anyways.....
Drawbacks? I think there's a couple:
-Obviously you now have a whole other library to deal with, include, etc.
-Some previous smarty versions had some ridiculous syntax for loops and other stuff that should have been simple.
-When you need to put a simple javascript statement somewhere in your template, like this:
<script type='text/javascript'>
$(document).ready(function(){
//foo
});
</script>
ok, you might include that in a js file instead of inline, but there's a lot of cases where you just need those couple of lines of js. smarty doesn't like the curly braces and you have to wrap them in an ugly tag that looks like this:
{literal}{\literal}
in that case so much for making your code any cleaner....
If I had to choose, I probably would just use the non-standard short-form tag and be done with it.
We extensively use Smarty.
I would say it is dis-advantageous
in terms:
1. Parsing of smarty templates to PHP which make things slow
2. Your learning ablity to cope-up with smarty syntax.
It is advantageous in the sense:
Separation of Business logic from the Presentational logic.
If you need display helpers, it would be helpful towards DRY principle. (Just like helpers in erb - ROR)
Unless your product is going to be a large and ongoing product and if things are possible with PHP, avoid using Smarty.
I thought I'd give Smarty a try for my most recent project, just because some job postings I came across mentioned wanting experience in using it. I have not delved too deep into the documentation, just acquired a working knowledge to use on a rather simple site. Here are my impressions thus far-
The good
Most sites I have worked on, present project included, follow a fairly similar structure (template) from page to page. In the past, I have simply kept an updated blank template somewhere in the file structure and populated it with additional HTML or PHP on a case by case basis. One nice thing about Smarty is that you can store this general template in the Smarty Template directory and populate it using the {extends} function in the presentation page's template. For example, this would be the saved template (missing doctype, SO giving me a headache)-
`
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<meta http-equiv="Description" content="{block name=meta_description}{/block}" />
<title>My Smarty Site - {block name=pageTitle}{/block}</title>
{block name=additionalHeaders}{/block}
</head>
<body>
<div id="headerDIV">
<div id="nav-box">
<!-- Nav would go here -->
</div>
</div><!-- end #headerDIV -->
<div id="mainContainer">
<div id="generalContent">
<div id="pageTitle">
{block name=pageTitle}{/block}
</div>
{block name=pageText1}{/block}
<div id="page-bottom">
{block name=pageText2}{/block}
</div>
</div> <!-- end #generalContent -->
</div> <!-- end #mainContainer -->
</body>
`
and then populated like so:
{extends file="myTemplate.tpl"}
{block name=packageTitle}Simple Template{/block}
{block name=meta_description}This is a simple Smarty Template test{/block}
{block name=additionalHeaders}
<link rel="stylesheet" type="text/css" href="/css/smarty_test.css"/>
{/block}
{block name=pageText1}
<p>Hello, {$name}! This is a Smarty Test.</p>
{/block}
{block name=pageText2}
<p>This is some more text....</p>
{/block}
So, rather than copying my template over and over again for each similar page, I simply extend it using Smarty with the content for that particular page. Another advantage to that is when I need to change some aspect of that template; rather than changing multiple pages, I change just that one (yes, similar to using a lot of PHP includes).
The Bad
While I know that Smarty has a lot of built in functions and can do some cool things, to really get the most out of it you have to learn its syntax. And, if you already know PHP, you're learning something entirely new to accomplish the same end result. Separation of logic and design is great until you need to make very dynamic page with lots going on - then you find yourself adding a lot of conditional statements, loops, etc. to the template using Smarty syntax and you realize that you might as well just use PHP.
I do plan on learning a bit more about Smarty, simply because it's used in a lot of apps I have come across and has been listed as a requirement for jobs, but I do not see myself using it that much in future projects of my own.