2

I discovered dōmo from Jed Schmidt which seems useful for creating server side HTML in node.js.

Basic stuff works but I lack to see how I can use loops like forEach() on arrays to create things like table rows. I created a basic example:

var domo = require('domo');

var fruits = [];
fruits.push("banana", "apple", "peach");

var document = DOCUMENT({type: "html"},
  HTML(
    HEAD(
      TITLE("bla"),
      SCRIPT({src: "/script.js"})
      ),
    BODY(
      TABLE(
        THEAD( TR( TD("Predicate"), TD("Object"))),
        TBODY(
          fruits.forEach(function(value, index) {
            console.log("I am in forEach");
            console.log("Value: "+value);
            console.log("Key: "+index);
            TR(
              TD(index),
              TD(value)
              )
          })
          )
        )

      )
    )).outerHTML;

console.log(document);

This currently results in this output:

<!DOCTYPE html>
<html>
    <head>
        <title>
            bla
        </title>
        <script src="/script.js" type="text/javascript">
</script>
    </head>
    <body>
        <table>
            <thead>
                <tr>
                    <td>
                        Predicate
                    </td>
                    <td>
                        Object
                    </td>
                </tr>
            </thead>
            <tbody>
                <!--undefined-->
            </tbody>
        </table>
    </body>
</html>

If I get that correctly I cannot access the scope of domo within the forEach loop. Is this the right interpretation and what would be the correct working way to do that?

Solution:

Thanks to the hint from Bergi and a fix by Jed Schmidt this fragment now works (domo >=0.5.5):

TBODY( fruits.map(function(value, index) {
  return TR(
    TD(String(index)),
    TD(value)
    );
}))
)
4

1 回答 1

3

forEach returns undefined after having iterated the array.

I don't know whether those functions accept arrays as arguments, but you might try map:

TBODY( fruits.map(function(value, index) {
    console.log("I am in map");
    console.log("Value: "+value);
    console.log("Key: "+index);
    return TR(
//  ^^^^^^ dont forget this
        TD(index),
        TD(value)
    );
}))
于 2012-11-13T21:16:33.283 回答