Search code examples
javascriptcoffeescriptdocpadeco

Integers Being Added to Array


I'm trying to use an array of objects to simplify maintaining a list of HTML buttons. Here's my code:

<% links = [{url:"https://github.com/drguildo", icon:"github"}, %>
<% {url:"http://www.flickr.com/photos/drguildo/", icon:"flickr"}, %>
<% {url:"http://instagram.com/therac25", icon:"instagram"}, %>
<% {url:"http://www.last.fm/user/drguildo", icon:"lastfm"}] %>
<% for link in links: %>
<a href="<%= link.url %>"><img src="/img/icons/<%= link.icon %>.png" /></a>
<% end %>

The problem is the resulting array looks like this:

[object Object],16,[object Object],17,[object Object],18,[object Object]

which messes up the output. Why are the objects interspersed with integers and how can I prevent it?

I'm probably doing this in a very sub-optimal way (I'm new to DocPad, ECO and CoffeeScript) so any suggestions on how to improve my code would be appreciated.


Solution

  • You don't want to be creating an array like this within the template. The point of eco templates it to separate the logic/data from the presentation. Declare the data separately, then use it to render the template.

    Like this

    eco = require "eco"
    fs  = require "fs"
    
    template = fs.readFileSync __dirname + "/views/test.html.eco", "utf-8"
    console.log eco.render template, links: [
        {url:"https://github.com/drguildo", icon:"github"}, 
        {url:"http://www.flickr.com/photos/drguildo/", icon:"flickr"},
        {url:"http://instagram.com/therac25", icon:"instagram"},
        {url:"http://www.last.fm/user/drguildo", icon:"lastfm"}
    ]
    

    and then just

    <% for link in @links: %>
    <a href="<%= link.url %>"><img src="/img/icons/<%= link.icon %>.png" /></a>
    <% end %>