Sails基础之View层——更换模板引擎

Sails内置了ejs模板引擎,如果想要更换模板引擎,可以参考:https://sailsjs.com/documentation/concepts/views/view-engines

安装swig模板引擎:

npm install consolidate --save
npm install swig --save
npm install swig-extras --save

配置swig模板引擎

module.exports.views = {

  extension: 'swig',
  getRenderFn: function () {

    const cons = require('consolidate');
    const swig = require('swig');
    const extras = require('swig-extras');
    
    swig.setFilter('round', function (input) {
      let num = parseInt(input);
      return Math.round(num);
    });

    swig.setFilter('numberFormat', function (input) {
      let num = parseInt(Number(input));
      if (num != null && num) {
        return num.toFixed(0).replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, '$&,');
      } else {
        return "0";
      }
    });

    //extra
    extras.useFilter(swig, 'split');
    
    cons.requires.swig = swig;
    
    return cons.swig;
  },

  layout: false

};

If layouts aren’t your thing, or (for now) if you’re using a server-side view engine other than ejs, (e.g. Jade, handlebars, haml, dust) you’ll want to set layout:false in sails.config.views and rely on your view engine’s custom layout/partial support.

我们为Sails设置了新的模板引擎swig,并且设置了swig的两个过滤器round和numberFormat,和一个扩展的过滤器split。
下面我们创建swig模板:
layouts/layout.swig:

<!DOCTYPE html>
<html>
    <head>
        <title>{% block title -%}{%- endblock %}</title>
    </head>
    <body>
        {% block content -%}
        {%- endblock %}
    </body>
</html>

pages/home.swig:

{% extends '../layouts/layout.swig' -%} 
{% block title -%}Home{%- endblock %}

{% block content -%}
<div>
    Hello {{name}}
    <br/>
    The number is {{number|numberFormat}}
    <br/>
    <div>
    {{__('Welcome')}}
    </div>
</div>
{% include "passport.swig" ignore missing %}
{%-endblock %}

生成Controller并配置route进行测试:

sails generate controller home

HomeController.js:

home: function(req, res){
        return res.view('pages/home', {
            name: 'xreztento',
            number: 100000
        });
    }

route:

  '/home': 'HomeController.home',

相关推荐
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页