2
votes

I'm developing a simple web site where I need to retrieve a list of objects from a database. I wanted to try nodejs so, after days of reading and tests, I finally decided to use this configuration:

  • Server technology: Nodejs + Express
  • Template engine: Dust
  • Database/Data source: Parse

I wired all these stuff and it seems working well, but I have now the first problem: I need to call a function from a Dust template, this is the code:

{>layout/}

{<content}
    <ul>
        {#photos}
        <li>{photo.get("name")}{~n}</li>
        {/photos}
    </ul>                
{/content} 

but it doesn't work because it prints out {photo.get("name")} (literally) instead of printing the name of each photo. The query with Parse works correctly as I can see the loaded objects via console.log().

I'm new both with nodejs and dust so I'm not sure the problem is related only to dust. Any idea?

1
What solution did you decide on in the end? - Elliot Lings

1 Answers

2
votes

I have no any other solution except creation of a helper:

var dust = require('dustjs-linkedin');

dust.helpers.exec = function(chunk, context, bodies, params) {
    var args = JSON.parse(params.args.replace(/'/g, '"'));
    var object = context.stack.head;

    params.func.split('.').some(function(property) {
        if (typeof(object[property]) === "function") {
             var result = object[property].apply(object, args);
             chunk.write(result);
             return true;
        } else {
            object = object[property];
            return false;
        }
    })

    return chunk;
};

Suppose we have following data:

app.get('/dust-test', function(req, res) {

    function Photo(name) {
        var props = {'name': name};

        this.get = function(prop) {
            return props[prop];
        }
    }

    var photos = ['foo', 'bar', 'nanana'].map(function(name) {
        return new Photo(name);
    })

    res.render("dust-test", {
        photo: new Photo('me'),
        photos: photos
    });
});

Usage:

<li>{@exec func="photo.get" args="['name']" /}</li>

{#photo}
    <li>{@exec func="get" args="['name']" /}</li>
{/photo}

<ul>
    {#photos}
    <li>{@exec func="get" args="['name']" /}{~n}</li>
    {/photos}
</ul>

Where args - is an array of arguments in json format (single quotes are used)