Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Calling helper functions inside templates #175

Closed
stnever opened this issue Sep 10, 2015 · 4 comments
Closed

Calling helper functions inside templates #175

stnever opened this issue Sep 10, 2015 · 4 comments
Labels

Comments

@stnever
Copy link

stnever commented Sep 10, 2015

I have several different templates, each in their own file, in which I need to show dates, like the following:

Hello {{= it.name}} on {{= u.d(it.date)}}!

I'd like to format that date, using moment.js, and also add some logic to print unknown when the date is null. Because that happens in a lot of places I created a helper:

var moment = require('moment');
function d(date) {
  if ( date == null ) return 'unknown';
  return moment(date).format('YYYY-MM-DD');
}

But I can't find a way to call that function inside the template. I'm using Node, so I don't want to pollute the global namespace. I even tried putting that in an utility object and require-ing it at the top of my template, to no avail:

{{ var u = require('./utils.js'); }}
Hello {{= it.name}} on {{= u.d(it.date)}}!

FWIW, the generated template function above looks like this:

function anonymous(it) {
  var out=''; var u = require('./utils.js'); out+='\r\n\r\nHello '+( it.name)+' on '+( u.d(it.date))+'!';return out;
}

and the error is

 ReferenceError: require is not defined
      at Context.<anonymous> (test/email-templates/test-dot.js:14:23)
@zlumer
Copy link

zlumer commented Sep 10, 2015

One option would be to pass the function directly to your template:

Hello {{= it.name }} on {{= it.d(it.date) }}!
var tmpl = anonymous({ name:"John", date:123241, d:require('./utils').d });

@Runaria
Copy link

Runaria commented Oct 22, 2015

    var dT = require('doT');
    var tpl = {
         tmpl:dT.template('{{=this.helper()}}'),
         helper: function(){
               /* do what you want to do */
         }
    }
    tpl.tmpl(); // render template

or

    // helper functions
    var helper = {
        sum: function(x,y){
            return x+y
        }
    }
    // template
    render = dT.template('{{=this.sum(it.x, it.y)}}');
    // call render
    render.call(helper, {x:5, y:6});

@epoberezkin
Copy link
Collaborator

probably can be added to documentation

@epoberezkin
Copy link
Collaborator

add to doT 101 #205

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

4 participants