Since I started trying to write ajax applications, one thing I seem to run into very frequently is, I guess, the issue of templating. I have spent countless hours attempting to write my php templates as DRY as possible. I have made sure that template code is defined in one place only. On the server side, this is a piece of cake. When you start bringing ajax functions into it, it gets a bit tougher. Let's say I have the following html code (simplified for brevity):
Code: Select all
<ul id="selections">
<li class="item"><a href="/barker/bob/">Bob Barker</a></li>
<li class="item"><a href="/jones/jenny/">Jenny Jones</a></li>
<li class="item"><a href="/reiner/rob/">Rob Reiner</a></li>
<li class="item"><a href="/wonka/willy/">Willy Wonka</a></li>
</ul>
In the back-end, I'd represent this code something like this:
Code: Select all
<ul id="selections">
<?php foreach ($this->people as $person): ?>
<li class="item"><a href="<?php echo $this->url("person", array('person' => $person->getPk())); ?>"><?php echo $person->getFullName(); ?></a></li>
<?php endforeach ?>
</ul>
With me so far? OK. Now, let's introduce ajax. What happens when I want to dynamically update this list with ajax when a user performs some kind of action? How do I ensure that my ajax knows how to put the html together when it adds to the list? Honestly what I'm doing right now is just duplicating code. I'm basically writing the template in two places... in my php template and in my ajax functions.
Code: Select all
$(function() {
$("#selections").click(function() {
person = getPerson(); // some made-up function
var html = "<li class='item'><a href='" + person.url + "'></a>" + person.fullname + "</li>";
$(this).append(html);
});
});
How do people usually do this?
