sports
sports

Reputation: 8147

Selecting with jquery in my own js templating system/engine

For simplification and control, I have my own js templating engine, which works like this:

html:

 <ul id="persons">
    <li class="person-template hide">
       <span>{name}</span>, <span class="placemark" data-lat="{latitude}" data-lng="{longitude}">{location}</span>
    <li>
 </ul>

js:

 var persons = [
       {"name":"hulk", "location": "usa", latitude: -33.4, longitude: -70.5}, 
       {"name":"wolverine", "location": "mexico", latitude: -33.4, longitude: -70.5}, 
 ];


 $.each(persons, function(i, person) {
      var html = $(".person-template").clone().removeClass("person-template").addClass("person").show().outerHtml();

      html = html.replaceAll("{name}", person.name);
      html = html.replaceAll("{latitude}", person.latitude);
      html = html.replaceAll("{longitude}", person.longitude);
      html = html.replaceAll("{location}", person.location);
 });

(replaceAll and outerHtml are two helper functions I've made, they are self-explained by their names)

My problem with this is that sometimes I want to select things with jQuery but my template notation interferes, for example:

$(".placemark").each(function(i, v) {
     alert($(v).data("latitude")));
});

Will alert: "{latitude}", "-33.4", "-33.4"
Obviously I want to avoid the template value.

What is the most clean solution for this?

  1. Start using a formal template engine?
  2. Skip first in the $.each? (kind of ugly)
  3. ...?

Upvotes: 0

Views: 34

Answers (1)

Alien Life Form
Alien Life Form

Reputation: 591

You are cloning the template, so it still exists. You need to remove it after you loop through.

$(".person-template").remove();

or, you can just make sure not to grab the person-template when you alert. $(".location_but_not_location_template").each ...

Upvotes: 1

Related Questions