• nodejs前端模板引擎swig入门


    https://www.jianshu.com/p/f0bffc42c1ce

    相对于jade,我还是更喜欢swig前端模板引擎,jade虽然语法简练高效了不少,但是在我这最大的问题是

    他没有一个html该有的样子。。。

    所以我还是决定使用swig,页面结构,样子都是熟悉的样子,使用起来顺手了许多。
    很多朋友也在纠结二者的优缺点,这个根据需求因人而异吧

    这是两者的比较
    http://vschart.com/compare/swig-template-engine/vs/jade-template-engin


    下面我们一起学习下swig这个前端模板引擎

    swig的简单介绍

    swig是JS模板引擎,它有如下特点:

    • 支持大多数主流浏览器。
    • 表达式兼容性好。
    • 面向对象的模板继承。
    • 将过滤器和转换应用到模板中的输出。
    • 可根据路劲渲染页面。
    • 支持页面复用。
    • 支持动态页面。
    • 可扩展、可定制。

    一. swig的安装

    npm install swig --save
    

    二.和express框架集成

    app.js

    var express = require('express');
    var swig = require('swig');
    var path = require('path')
    
    var app = express();
    var port = process.env.PORT || 4000
    
    //设置swig页面不缓存
    swig.setDefaults({
      cache: false
    })
    app.set('view cache', false);
    
    app.set('views','./views/pages/');
    app.set('view engine','html');
    app.engine('html', swig.renderFile);
    
    
    app.listen(port);
    
    console.log('server is started at http://localhost:'+port);
    
    //index page
    app.get('/',function(req, res){
        res.render('index',{
            title:'首页 ',
            content: 'hello swig'
        })
    })
    
    

    index.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>{{ title }}</title>
    </head>
    <body>
        {{ content }}
    </body>
    </html>
    

    然后测试运行

    node app.js
    

    在浏览器输入:http://localhost:4000, 执行效果如下

     
    浏览器运行.png

    三.基本用法

    1.变量

    {{ name }}
    

    这里需要注意的是前后两端都要有空格,这样{{name}}写就会报错

    2.属性

    {{ student.name }}
    

    3.模板继承

    Swig 使用 extends 和 block 来实现模板继承 layout.html

    首先我们定义一个模板

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>{% block title %}{% endblock  %}</title>
        {% block head %}{% endblock  %}
    </head>
    <body>
        {% block content %}{% endblock  %}
    </body>
    </html>
    

    这个模板里面我们定义了三个block块,子模板可以对这三个block继承

    然后我们写一个index.html继承这个模板

    {% extends './layout.html' %}
    {% block title %} index {% endblock %}
    {% block content %}
        <div>
                <h1>hello swig</h1>
         <div>
    {% endblock %}
    

    注意我这里并没有复写{% block head %}{% endblock %}这个块

    也就是说我们可以在layout.html模板页面里面定义很多block,而子页面可以有选择性的实现。

    4.include模板

    包含一个模板到当前位置,这个模板将使用当前上下文

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>{% block title %}{% endblock  %}</title>
        {% include "./includes/head.html" %}
        {% block head %}{% endblock  %}
    </head>
    <body>
        {% include "./includes/header.html" %}
        {% block content %}{% endblock  %}
    </body>
    </html>
    

    5.if判断

    { % if name === '郭靖' % }
      hello 靖哥哥
    { % endif % }
    

    6.if-else判断

    { % if name === '郭靖' % }
      hello 靖哥哥
    { % elseif name === '黄蓉' % }
      hello 蓉妹妹
    { % else % }
      hello 欧阳峰
    { % endif % }
    

    7.for循环

    先上栗子:

    // arr = [1, 2, 3]
    { % for key, val in arr % }
      <p>{ { key } } -- { { val } }</p>
    { % endfor % }
    

    for循环内置变量:

    • loop.index:当前循环的索引(1开始)
    • loop.index0:当前循环的索引(0开始)
    • loop.revindex:当前循环从结尾开始的索引(1开始)
    • loop.revindex0:当前循环从结尾开始的索引(0开始)
    • loop.key:如果迭代是对象,是当前循环的键,否则同 loop.index
    • loop.first:如果是第一个值返回 true
    • loop.last:如果是最后一个值返回 true
    • loop.cycle:一个帮助函数,以指定的参数作为周期

    使用方法:

    // arr = [1, 2, 3]
    { % for key, val in arr % }
      <p>{{ loop.index }} -- {{ key }} -- {{ val }}</p>
    { % endfor % }
    

    8.强大的内置过滤器

    • add(value):使变量与value相加,可以转换为数值字符串会自动转换为数值。
    • addslashes:用 转义字符串
    • capitalize:大写首字母
    • date(format[, tzOffset]):转换日期为指定格式
    • format:格式
    • tzOffset:时区
    • default(value):默认值(如果变量为undefined,null,false)
    • escape([type]):转义字符
    • 默认: &, <, >, ", '
    • js: &, <, >, ", ', =, -, ;
    • first:返回数组第一个值
    • join(glue):同[].join
    • json_encode([indent]):类似JSON.stringify, indent为缩进空格数
    • last:返回数组最后一个值
    • length:返回变量的length,如果是object,返回key的数量
    • lower:同''.toLowerCase()
    • raw:指定输入不会被转义
    • replace(search, replace[, flags]):同''.replace
    • reverse:翻转数组
    • striptags:去除html/xml标签
    • title:大写首字母
    • uniq:数组去重
    • upper:同''.toUpperCase
    • url_encode:同encodeURIComponent
    • url_decode:同decodeURIComponemt

    使用方法:
    例如我们要格式化一个时间,使用方法和linux上的管道命令非常像

    {{ birthday|date('Y-m-d') }}
    

    大写首字母

    {{ name|title }}
    

    9.set命令

    用来设置一个变量,在当前上下文中复用

    {% set foo = [0, 1, 2, 3, 4, 5] %}
     {% for num in foo %}
        <li>{{ num }}</li>
    {% endfor %}
    

    参考文献
    http://www.iqianduan.net/blog/how_to_use_swig
    http://jinfang.oschina.io/posts/124966c9/



    作者:程序鱼
    链接:https://www.jianshu.com/p/f0bffc42c1ce
    來源:简书
    简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。
  • 相关阅读:
    日期计算
    普通二叉树转换成搜索二叉树
    每周行情
    virtualbox安装增强功能时【未能加载虚拟光盘】
    linux实用命令之如何移动文件夹及文件下所有文件
    Linux文件夹文件创建、删除
    php 克隆 clone
    function_exists (),method_exists()与is_callable()的区别
    webgrind安装使用详细说明
    windows下redis的安装配置和php扩展使用phpredis
  • 原文地址:https://www.cnblogs.com/beimingbingpo/p/9915890.html
Copyright © 2020-2023  润新知