zoukankan      html  css  js  c++  java
  • 在Express中安装XTemplate

    上一节讲了安装Express,并且生成了一个"microblog"的工程,我们的目标是在工程下安装XTemplate:

    1.安装xtpl

    npm install xtpl xtemplate --save 

    2.在views目录添加test.xtpl文件,其内容为

    this is {{title}}!

    3.可以做一个简单的测试,判断xtpl是否安装成功

    var xtpl = require('xtpl');
    xtpl.renderFile('./views/test.xtpl',{
    title:'Express'
    },function(error,content){
    console.log(content);
    });

    输出:this is Express!

    4.集成到Express中,只需要在app.js中,设置模板引擎即可

    app.set('view engine', 'xtpl');

    5.测试一个路径

    var print = require('./routes/print');
    app.use('/ooxx', print);

    在print.js中
    var express = require('express');
    var router = express.Router();
    router.get('/', function(req, res) {
    res.render('test', { title: 'Express' });
    });
    module.exports = router;

    6.此时如果在浏览器输入:127.0.0.1:3000/ooxx

    显示为:this is Express!

    需要注意的是,如果要自定义Express的模板引擎,是需要

      Use the app.engine(ext, callback) method to create your own template engine. ext refers to the file extension, callbackis the template engine function which accepts the location of the file, the options object, and the callback function, as its parameters.

    The following is an example of implementing a very simple template engine for rendering ".ntl" files.

    var fs = require('fs'); // this engine requires the fs module
    app.engine('ntl', function (filePath, options, callback) { // define the template engine
      fs.readFile(filePath, function (err, content) {
        if (err) throw new Error(err);
        // this is an exteremly simple template engine
        var rendered = content.toString().replace('#title#', '<title>'+ options.title +'</title>')
        .replace('#message#', '<h1>'+ options.message +'</h1>');
        return callback(null, rendered);
      })
    });
    app.set('views', './views'); // specify the views directory
    app.set('view engine', 'ntl'); // register the template engine
    

    Your app will now be able to render ".ntl" files. Create a file named "index.ntl" in the views directory with the following content.

    #title#
    #message#
    

    Then, create the following route in your app.

    app.get('/', function (req, res) {
      res.render('index', { title: 'Hey', message: 'Hello there!'});
    })

    其链接为:http://expressjs.com/advanced/developing-template-engines.html

    也就是说要配置xptl的renderFile函数才行,不过为什么不用配置是可以的,后续还要看下

  • 相关阅读:
    shell脚本,文件里面的英文大小写替换方法。
    shell脚本,100以内的质数有哪些?
    shell脚本,当用sed删除某一文件里面的内容时,并追加到同一个文件会出现问题。
    shell脚本,按行读取文件的几种方法。
    shell脚本,锁机制
    shell脚本,通过一个shell程序计算n的阶乘。
    shell脚本,如何写进度条。
    shell脚本,判断给出的字符串是否相等。
    shell脚本,按空格开始60秒的倒计时。
    18:django 日志系统
  • 原文地址:https://www.cnblogs.com/fuland/p/4041666.html
Copyright © 2011-2022 走看看