2

I'm sure I'm doing pretty simple wrong but can't seem to find an explanation. I've got the following line in my template which is not printing any values to the html output:

  <%= _.each(@place.get("hash"),(count, tag) -> "#{tag} ") %>

This line is printing values to the console perfectly fine:

  <%= _.each(@place.get("hash"),(count, tag) -> console.log "#{tag} ") %>

When I try using a print command and refresh, google chrome throws up a print menu. How can I resolve this

socratic_singh
  • 183
  • 1
  • 13

3 Answers3

6

In addition to the useful Underscore methods mu is too short mentioned, you can also use CoffeeScript's native for of in Eco:

<% for tag of @place.get("hash"): %>
  <%= tag %>
<% end %>

This can be useful in case you need to add some markup around each element. For example:

<ul>
  <% for tag of @place.get("hash"): %>
    <li><%= tag %></li>
  <% end %>
</ul>
Community
  • 1
  • 1
epidemian
  • 18,817
  • 3
  • 62
  • 71
  • Unfortunately this wasn't working; did a bit of digging and needed to replace 'in' with 'of' when iterating through hashes.Definitely better when you need markup though - thanks! – socratic_singh May 09 '12 at 23:00
  • 1
    @socratic_singh Ups, i totally missed that this was an object instead of an array what was being iterated. I updated the answer to use `of` instead of `in` so it doesn't mislead possible future readers hehe. Thanks for pointing it out! – epidemian May 10 '12 at 00:56
2

Underscore's each doesn't return anything so <%= _.each(...) %> doesn't do anything useful. You could use _.map and join:

<%= _(@place.get('hash')).map((count, tag) -> tag).join(' ') %>

or you could use _.keys and join:

<%= _(@place.get('hash')).keys().join(' ') %>

Your _.each is just extracting the keys so you should say what you mean.

If you're using node.s then you should have Object.keys as well:

<%= Object.keys(@place.get('hash')).join() %>
user3335966
  • 2,673
  • 4
  • 30
  • 33
mu is too short
  • 426,620
  • 70
  • 833
  • 800
0

Here is an example to iterate over an hash with underscore's _.each method:

Given the hash:

articlesByMonth = {'2014-07': [{id: 1, title: 'foo'}, {id: 2, title: 'bar'}]}

combined with an template:

<ul>
  <% _.each articlesByMonth, (articles, month) =>: %>
    <%= month %>
    <ul>
      <% _.each articles, (article) =>: %>
        <li><%= article.title %></li>
      <% end %>
    </ul>
  <% end %>
</ul>
fluxsaas
  • 997
  • 2
  • 11
  • 27