1

Currently I'm echoing html elements using php. Other times, I need to use javascript and create this elements dinamically (for example, some functions in mobile work differently and need some tweaks in the DOM). Unfortunately I'm spanning two different dimensions of elements (or more) in the code and need to update all of them if I want to change something. As an example:

Streaming long polling with javascript (jQuery):

...append("<div></div><div></div><div></div><div></div>");

PHP echo

echo "<div></div><div></div><div></div><div></div>";

Something other in php with for each echo

foreach(...){
    echo "<div></div>";echo "<div></div>";
    (...)
    foreach(...){
       echo "<div></div>";
       echo "<div></div>"
    }
}

If I want to change the structure of this element I would have to change ALL of the 3 situations, from 4 divs to 2 divs or 1 for example. How exactly could I centralize all this elements throughout php and javascript? I thought of having a string in php and spanning as templates to javascript but it gets messed up when making dynamic classes and other properties because of concatenation. Does anyone know of another way to do this?

Fane
  • 1,978
  • 8
  • 30
  • 58

1 Answers1

1

PHP

The most efficient way to output HTML with PHP is aggregating everything in a single variable and printing out once.

$html = '';

foreach ($rows as $key => $value) {
  $html .= $value;
  // You may nest loops as long as you want.
}

print $html;

Here is an article about creating a simple templates How to make a simple HTML template engine in PHP

JavaScript I can't relate to jsperf.com, since it's down. But the most efficient way to append HTML Nodes is by creating them before append. The approach is described in What is the most efficient way to create HTML elements using jQuery?

// The fastest you could get.
$(document.createElement('div'));

// That's for your case.
$("<div></div><div></div><div></div><div></div>").appendTo(target);

It's hard to recommend on which technology you should focus, it mostly depends on your priorities. Some websites are static and store their HTML in static HTML files, eg. Jekyll

Some sites are so dynamic and change a lot with user input, one of the best libraries for rendering HTML on client is React.js

If your website is static, then make simple template engine in PHP, if your website relies on user input a lot, then go with React.js, but don't even think of making front-end render with jQuery, you will waste your time.

If React.js looks too complex, I would recommend using Mustache Templates

Community
  • 1
  • 1
halfzebra
  • 6,771
  • 4
  • 32
  • 47
  • I like the approach related to the html template. Is there anyway of getting the template file in javascript? – Fane Jul 20 '15 at 00:08
  • @Fane yes, there are [Mustache Templates](https://github.com/janl/mustache.js) and [jQuery Template](https://github.com/codepb/jquery-template) from the easiest. – halfzebra Jul 21 '15 at 08:45