Reputation: 1061
I have been reviewing my code trying to tidy it up, and I am just getting sick of the way I write jQuery when it needs to copy html from the page. Here is what I mean:
I have a section of the page that loops through posts like a forum (my actual code is more html heavy):
<? foreach ($posts as $post): ?>
<div class="post">
<div class"post_details">
<a href="<?= $post->link ?>"><?= $post->title ?></a>
<br>
<?= $post->timestamp ?>
</div>
</div>
<? endforeach ?>
And then in my jquery, I essentially have to duplicate this HTML to loop through the results of an AJAX request to get more recent posts:
for (i = 0; i < response.length; i++) {
post = respnse[i];
html = '<div class="post">';
html += '<div class"post_details">';
html += '<a href="' + post.link + '">' + post.title + '</a>';
html += '<br>';
html += post.timestamp;
html += '</div>';
html += '</div>';
}
// Inject html into page
$(".feed").prepend(html);
If I change the layout of the HTML where PHP loops through the object, then I also have to change the HTML in the jQuery. I then end up with lots of essentially duplicated code which just becomes messy as anything.
Is there a way to better link the jQuery to the HTML elements to make the code more concise?
Upvotes: 1
Views: 207
Reputation: 26076
You should use the server-side template -> client-side template. The approach is straight forward and results in you modifying only the server-side template in maintenance in most cases.
Step 1. Define a server-side function or block
<?php
function postTemplate($post) { ?>
<div class="post">
<div class"post_details">
<a href="<?= $post->link ?>"><?= $post->title ?></a>
<br>
<?= $post->timestamp ?>
</div>
</div>
<? } ?>
Step 2. output it onto the page for client-side templating (using specific client-side syntax for whatever your client-side choice i.e. Moustache)
<script type="html/template" id="postTemplate">
<?php
$obj = new stdClass;
$obj->link = "{link}";
$obj->title = "{title}";
$obj->timestamp = "{timestamp}";
echo postTemplate($obj);
?>
</script>
Step 3. Use your favorite client-side templating strategy
<script>
// refer to http://mustache.github.com/
// but I prefer EJS myself
</script>
Upvotes: 1
Reputation: 606
Your method is crazy...
html = '<div class="post">';
html += '<div class"post_details">';
html += '<a href="' + post.link + '">' + post.title + '</a>';
html += '<br>';
html += post.timestamp;
html += '</div>';
html += '</div>';
Why do this in JavaScript? Why not have the PHP return the fully formatted string and then just use jQuery to put it into its place? Just return this in an xml string and extract it.
Better yet, have the AJAX request return a View (if you're using an MVC framework) that runs that exact code. Put the code in one place, a partial view or something and create a link to that that you can AJAX to. My $0.02.
Upvotes: 2