Adding large quantities of HTML with Jquery/javascript - php

I'm working on a form that auto-generates a large addition when the user specifies, including a editable canvas, selectable inputs, textareas and so on. I'm wondering if there's a tool for appending large blocks of HTML more easily and with better style: for instance, in my codeigniter PHP views it's easily done just by closing the PHP tag and referencing variables using <?=var?>.
<?php if (condition) {?>
<h1>List a variable <?=$var?></h1>
<?php }?>
Is the above terrible style? Is there a comparable tool to use for javascript so I can include html with proper indentation?
EDIT:
To be clearer, I'm not looking for a lot of input on the php - my objective is to make editing the HTML I'm inserting with javascript cleaner.
The problem is analogous to this:
<?php
if (condition) {
echo "<div>";
echo "<p> a line of html code<p>";
echo "<h1> more stuff and a ".$variable;
echo "<div>";
}
?>
//vs
<?php
if (condition) { ?>
<div>
<p> A line of html code, but easier to edit</p>
<h1> a <?=$var?>
</div>
<? } ?>
The second one is cleaner and easier to edit for the developer. So I'd like to do the same with javascript and take this:
$(this).append('<p>a whole bunch of stuff'+var+'more stuff<p>');
$(this).append('<p>more stuff<p>');
$(this).append('<h1>more stuff<h1>');
And make it easier to manage.

Indentation is for the DEVELOPER, to make source code maintainable and readable. It has nothing to do with making "view source" look nice.

It does look a little unpleasant, certainly.
I'd probably write it like this, if I was using that particular approach to page generation.
<?php
if (condition)
echo "<h1>List a variable $var</h1>";
?>
You may also like to look into the DOM methods of php. They can make creating reusable, modular code much easier.
They're not as fast as simple string operations, but far neater and more powerful. When the daily traffic means this difference in speed is a problem you've probably got the money to throw at some ode monkey to make the required changes.

Try CoffeeScript. It adds some features to normal javascript like string interpolation, block strings and stuff that makes writing huge blocks of HTML string literals a piece of cake.

Related

PHP - start / end PHP multiple times in HTML file

I have a HTML file where I am using PHP like this:
...
<?=$someVariable;?>
<html code>
<?php do something ?>
<?php do something ?>
<div>
<?php do something ?>
</div>
<?php do something ?>
...
Is this a good way to go, or should I put entire HTML to PHP echo? I mean, I am starting / stopping script inside web page multiple times just because of one output one variable or if some block of the HTML code.
I am doing it this way fo better readibility of HTML/PHP code during development.
Your question of "which way is better" can be broken down into two questions:
Which way is more efficient?
Which way is more readable?
The answer to question 1 is that the difference is negligible. PHP code is made to execute very fast on the server. Usually processes that take long on PHP would be complex functions that require iterations over large amounts of data for instance, however the actual reading of a single tag takes a very small amount of time to be processed.
The answer to question 2 depends entirely on the situation. In your situation, you are constantly adding <?php and ?> tags when you could have done it all at once, so my personal opinion would be to place it all in one echo, however there are many cases where it is more readable to place separate php elements, for example in the following form:
<form action="<?php htmlspecialchars($_SERVER['PHP SELF']);?>" method="POST">
<?php echo $dynamic_input1'?><br>
<input type="text" name="text1">
<?php echo $dynamic_input2'?><br>
<input type="text" name="text2">
</form>
Let me know if that helped.
You should start to use templates (read: viewmodels).
To keep readable the HTML you can move to logic to the top of PHP file and leave only the variable printing into the HTML code.
I'm not really a fan of multiple html/php blocks. What I normally use is heredoc, here's an example:
<?php
$myTitle = "Heredoc is Cool";
$myArray = array(array('someIndex' => '1st Paragraph'), array('anotherIndex' => '2nd Paragraph'));
echo <<< LOL
<!DOCTYPE html>
<html>
<head>
<title>{$myTitle}</title>
</head>
<body>
<h1>{$myArray['0']['someIndex']}</h1>
<p>{$myArray['1']['anotherIndex']}</p>
</body>
</html>
LOL;
?>
Using heredoc helps me write code without the need of concatenation, quotes and several blocks of php between html, which can be confusing sometimes. Heredoc also helps my code to be more readable.
This reduces the performance a little bit. too little. If you are more concerned about the readability of code, you can manage you code in different files and categorize the code (This is my personal technique). For Example a code for HTML 'Like' button will be like.txt file. Whenever I want to use the Like Button i just add
file_get_contents("like.txt");
This technique will increase flexibility of the code but again will reduce the performance a little (as you are opening files). For this technique to follow you have to maintain a class Architecture Diagram, Class Diagram, Use Case Diagram and other this.
This is the basic hurdle of programming (Quality Assurance). Increasing one thing may reduce another i.e. Increasing Interoperability and Flexibility will reduce Performance (depends how much). So you have to measure what you need the most in a particular Software project.

is this a good practice to output html using php? [duplicate]

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.

PHP/HTML - Spaghetti, fastest code for the server

I have a big page with much spaghetti code. I'm not sure which solution is faster for the server.
The first solution
<div> ... many html code ....
<?
if(isset($ubo['day']['xxl']['0']))
{
$firstHit = $ubo['day']['xxl']['0']['title'];
echo "<div style=\"cursor:pointer;\">$firstHit </div>";
}
?>
... many html code .... </div>
this solution ( I use ' instead of " )
<?
// many php code
if(isset($ubo['day']['xxl']['0']))
{
$firstHit = $ubo['day']['xxl']['0']['title'];
}
// one echo with all html code
echo "<div> ... many html code ....
<div style='cursor:pointer;'>$firstHit </div>
... many html code .... </div>";
?>
or this solution
<?
// many php code
if(isset($ubo['day']['xxl']['0']))
{
$firstHit = $ubo['day']['xxl']['0']['title'];
}
// one echo with all html code
echo "<div> ... many html code ....
<div style=\"cursor:pointer;\">$firstHit </div>
... many html code .... </div>";
?>
Practically, it doesn't really matter. What matters is that your code is maintainable and clean. You should look into using a PHP framework like CodeIgniter or CakePHP to make your code more well-structured.
You should have as little HTML inside PHP echo/print statements as possible; it is good to close PHP tags and just have the natural HTML. This is because the parser won't travel through the echo/print statement and and parse it. Thus, your first solution is certainly the best in terms of speed.
Of the solutions presented, I would say that the first is probably best. General rule is that you should put as much into strait HTML as possible. This is both for the developer's sake as well as the server's. Stuff outside of <?php ?> is basically raw data which, while it still needs to be parsed on some level, can basically be served to the user straight up.
If anything, you may want to refine it further:
<!-- as a note: in all of your examples except the first, this div exists.
In the first it only exists if the isset returns true. -->
<div style="cursor:pointer;">
<php?
if(isset($ubo['day']['xxl']['0']))
{
echo $ubo['day']['xxl']['0']['title'];
} ?>
</div>
You also could probably optimize through storing $ubo['day']['xxl'] in some local variable elsewhere on the page.
Do you have performance problem ? If no don't bother about "better for the server" and do "better for your code" instead.
And i'd say that all this is the same, most of the performance are due to I/O (sql query/web service, hard disk) not syntax details.
So do the best code for yourself you'll see later about performance.
The second solution might be faster than the first, because you are sending the content only once and it also looks a little better (PHP is more separated from HTML).
However performance difference between all 3 solutions will be very small and you really should't put attention to it.
Follow the hint "premature code optimization is evil" :-) I dont think that it makes a (big) difference what you use in your given code. It would be much better to have a clean code separation in mvc. Then you can use a template engine which supports caching for your massive html code and there's no need to output it every time with an echo! Besides this performance optimization has much more effect on DB-issues, your general code structure and the code at client side. For example, avoid inline css styles to reduce transferred html code.
do you use PHP opcode cache?
do you use memcached for generated subpages?
have you optimized your database queries?
do you use icongroup images? do you compress JS and CSS?
have you really run out of all the low hanging fruits?

Embedidng PHP code in HTML?

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 ?>

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