Вопрос

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:

<!doctype html>
<html lang="en">
<head>
    <title>app | {{=it.name}}</title>
</head>
<body>

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!

Это было полезно?

Решение

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top