Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to compile doT.js partials from a file into a string?

How to compile doT.js partials from a file into a string?

Problem

Hi I'm new to node and I'm trying to figure out how to Compile partials from a file into a string using doT.js (http://olado.github.io/doT/index.html).

/controllers/system/index.js:

var util = require( 'util' ),
    fs = require( 'fs' ),
    dot = require( 'dot' );

function System( ) {
    this.name = 'system';
}

System.prototype._loadFile = function( path, def ) {
    var def = def || { },
        tpl, str;

    str = fs.readFileSync( process.argv[ 1 ].replace( /\/[^\/]*$/, path ) );
    tpl = dot.compile( str );
    str = tpl( def );

    return str;
};

System.prototype._getHeaderContent = function( ) {
    return this._loadFile( '/controllers/system/views/header.html', {
        name: this.name
    });
};

System.prototype._getBodyContent = function( ) {
    return this._loadFile( '/controllers/system/views/main.html' );
};

System.prototype._getFooterContent = function( ) {
    return this._loadFile( '/controllers/system/views/footer.html' );
};

System.prototype.index = function( req, res, next ) {
    res.render( __dirname + '/../system/views/template', {
        header: this._getHeaderContent( ),
        body: this._getBodyContent( ),
        footer: this._getFooterContent( )
    });

    next ? next( ) : '';
};

module.exports = System;

/controllers/system/views/template.html:

{{=it.header}}
{{=it.body}}
{{=it.footer}}

/controllers/system/views/header.html:




    app | {{=it.name}}

In System.index when I call res.render template.html is being compiled but header.html is not. From that I assume render doesn't recursively render files and I need to manually compile header.html before I pass it in to res.render.

I found this tutorial: http://olado.github.io/doT/tutorial.html#compile but both .template and .compile return functions? Attempting to pass them in to res.render throws an error.

How do I compile them into strings? Or am I going about this the wrong way?

Thanks!

Update- fixed and updated with working code thanks Andreas Hultgren!

Problem courtesy of: Jonathan

Solution

dot.compile()or dot.template() returns a compiled function from a template string. Call it with or without data (compiledTemplate(data)) to get the generated template as a string. As a side-note, most template engines work this way.

Solution courtesy of: Andreas Hultgren

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

How to compile doT.js partials from a file into a string?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×