sstephenson / eco

Embedded CoffeeScript templates
MIT License
1.71k stars 70 forks source link

Getting data associated with a rendered template element #24

Closed maccman closed 13 years ago

maccman commented 13 years ago

Finding data associated with elements is a rather common use case. For example, let's say an element was clicked on, I'd love to be able to retrieve the data the element is associated with in the event handler. This is possible in jQuery.tmpl using $.fn.tmplItem(). Does eco have support, or plans for such a feature?

sstephenson commented 13 years ago

No, Eco deals exclusively with strings, not DOM nodes. You could build a wrapper to do this, though.

$.fn.eco = (data) ->
  template = $(this).text()
  $(eco.render template, data).data "ecoData", data

$.fn.ecoData = ->
  $(this).data "ecoData"
maccman commented 13 years ago

Unfortunately that doesn't work for iterations - I'm working on a helper that'll work a bit like this:

<% if @projects.length: %>
  <% for project in @projects: %>
    <%- item -> %>
      <a href="<%= project.url %>"><%= project.name %></a>
      <p><%= project.description %></p>
    <%- end %>
  <% end %>
<% else: %>
  No projects
<% end %>
metaskills commented 12 years ago

Nice example @sstephenson, but that seems to only work too if your templates are in the DOM somewhere vs in a JST space. Though this feature would be nice, I am going to continue to use eco and just have my controllers do the leg work of associating model data as things are rendered.