代码之家  ›  专栏  ›  技术社区  ›  Jonathan

如何将文件中的doT.js部分编译成字符串?

  •  0
  • Jonathan  · 技术社区  · 12 年前

    嗨,我是node的新手,我正试图弄清楚如何使用doT.js将文件中的部分编译成字符串( http://olado.github.io/doT/index.html ).

    /控制器/系统/索引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;
    

    /控制器/system/views/template.html:

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

    /控制器/system/views/header.html:

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

    在System.index中,当我调用res.render template.html时,正在编译,但header.html没有。由此,我假设render不会递归地渲染文件,并且在将其传递给res.render之前,我需要手动编译header.html。

    我找到了这个教程: http://olado.github.io/doT/tutorial.html#compile 但是.template和.compile都返回函数?试图将它们传递给res.render会引发错误。

    如何将它们编译成字符串?还是我的做法不对?

    谢谢

    更新-修复并更新了工作代码,感谢Andreas Hultgren!

    1 回复  |  直到 11 年前
        1
  •  1
  •   Andreas Hultgren    12 年前

    dot.compile() dot.template() 从模板字符串返回已编译的函数。使用或不使用数据进行调用( compiledTemplate(data) )以获取生成的模板作为字符串。顺便说一句,大多数模板引擎都是这样工作的。