koa-swig

引入库app.js

var render = require('koa-swig');

模版设置app.js

app.context.render = co.wrap(render({
root: __dirname + '/views',
autoescape: true,
cache: 'memory', // disable, set to false
ext: 'html'
}));

在another.js调用

router.get('/', function *(next) {
console.log(this);
yield this.render('index', {
title: 'Hello World'
}); });

这样就可以显示views/index.html了,后面的title设置的参数

前台页面的渲染

一. 继承layout.html页面的内容

index.html页面代码

{% extends 'layout.html' %}

{% block title %} {{title}} {% endblock%}

{% block cotent %} <p> 测试</p> {% endblock %}

layout.html页面代码

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta content="中文">
<title>{% block title %}My Site{% endblock %}</title>
</head>
<body>
{% block content %}{% endblock %}
</body>
</html>

index.html页面中的 block title 的内容会填入layout.html页面的block title中

二.也可以在页面中引入其它的页面

{% include "login.html" %}  

你可以标记 ignore missing,这样如果模板不存在,也不会抛出错误

{% include "foobar.html" ignore missing %}

如果想把本地声明的变量引入到包含的模板种,可以使用 with 参数来把后面的对象创建到包含模板的上下文中

{% set foo = { bar: "baz" } %}
{% include "inc.html" with foo %}
{% for bar in thing %}
{% include "inc.html" with bar %}
{% endfor %}

三、变量过滤器

1.demo

{{ name|title }} was born on {{ birthday|date('F jS, Y') }}
and has {{ bikes|length|default("zero") }} bikes.

也可以使用 filter 标签来为块内容添加过滤器

{% filter upper %}oh hi, paul{% endfilter %}

2、内置过滤器

  • 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

3、自定义过滤器

创建一个 myfilter.js 然后引入到 Swig 的初始化函数中

swig.init({ filters: require('myfilters') });

在 myfilter.js 里,每一个 filter 方法都是一个简单的 js 方法,下例是一个翻转字符串的 filter:

exports.myfilter = function (input) {
return input.toString().split('').reverse().join('');
};

你的 filter 一旦被引入,你就可以向下面一样使用:

{{ name|myfilter }}
{% filter myfilter %}
I shall be filtered
{% endfilter %}

四、条件语句

{% for x in y %}
{% if loop.first %}<ul>{% endif %}
<li>{{ loop.index }} - {{ loop.key }}: {{ x }}</li>
{% if loop.last %}</ul>{% endif %}
{% endfor %}
loop.index:当前循环的索引(1开始)
loop.index0:当前循环的索引(0开始)
loop.revindex:当前循环从结尾开始的索引(1开始)
loop.revindex0:当前循环从结尾开始的索引(0开始)
loop.key:如果迭代是对象,是当前循环的键,否则同 loop.index
loop.first:如果是第一个值返回 true
loop.last:如果是最后一个值返回 true
loop.cycle:一个帮助函数,以指定的参数作为周期 ```

在 for 标签里使用 else

{% for person in people %}
{{ person }}
{% else %}
There are no people yet!
{% endfor %}

if:条件语句

  • 参数:接受任何有效的 JavaScript 条件语句,以及一些其他人类可读语法
{% if x %}{% endif %}
{% if !x %}{% endif %}
{% if not x %}{% endif %}
{% if x and y %}{% endif %}
{% if x && y %}{% endif %}
{% if x or y %}{% endif %}
{% if x || y %}{% endif %}
{% if x || (y && z) %}{% endif %}
{% if x [operator] y %}
Operators: ==, !=, <, <=, >, >=, ===, !==
{% endif %}
{% if x == 'five' %}
The operands can be also be string or number literals
{% endif %}
{% if x|length === %}
You can use filters on any operand in the statement.
{% endif %}
{% if x in y %}
If x is a value that is present in y, this will return true.
{% endif %}

else 和 else if

{% if foo %}
Some content.
{% else if "foo" in bar %}
Content if the array `bar` has "foo" in it.
{% else %}
Fallback content.
{% endif %}

autoescape:改变当前变量的自动转义行为

  • 参数on:当前内容是否转义
  • 参数type:转义类型,js 或者 html,默认 html

假设

some_html_output = '<p>Hello "you" & \'them\'</p>';
然后

{% autoescape false %}
{{ some_html_output }}
{% endautoescape %}
{% autoescape true %}
{{ some_html_output }}
{% endautoescape %}
{% autoescape true "js" %}
{{ some_html_output }}
{% endautoescape %}

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

  • 参数name:变量名
  • 参数=:语法标记
  • 参数value:变量值
{% set foo = [, , , , , ] %} {% for num in foo %}
<li>{{ num }}</li>
{% endfor %}

macro:创建自定义可服用的代码段

  • 参数...: 用户定义
{% macro input type name id label value error %}
<label for="{{ name }}">{{ label }}</label>
<input type="{{ type }}" name="{{ name }}" id="{{ id }}" value="{{ value }}"{% if error %} class="error"{% endif %}>
{% endmacro %}

然后像下面使用

<div>
{{ input("text", "fname", "fname", "First Name", fname.value, fname.errors) }}
</div>
<div>
{{ input("text", "lname", "lname", "Last Name", lname.value, lname.errors) }}
</div>

输出如下

<div>
<label for="fname">First Name</label>
<input type="text" name="fname" id="fname" value="Paul">
</div>
<div>
<label for="lname">Last Name</label>
<input type="text" name="lname" id="lname" value="" class="error">
</div>

import:允许引入另一个模板的宏进入当前上下文

  • 参数file:引入模板相对模板 root 的相对路径
  • 参数as:语法标记 var: 分配给宏的可访问上下文对象
{% import 'formmacros.html' as form %}
{# this will run the input macro #}
{{ form.input("text", "name") }}
{# this, however, will NOT output anything because the macro is scoped to the "form" object: #}
{{ input("text", "name") }}

spaceless:尝试移除html标签间的空格

{% spaceless %}
{% for num in foo %}
<li>{{ loop.index }}</li>
{% endfor %}
{% endspaceless %}

参考:http://www.iqianduan.net/blog/how_to_use_swig

KOA 学习(五)koa常用库koa-swig的更多相关文章

  1. Koa 学习笔记

    开始 就像官网上说的,一切框架都从一个"Hello World"开始,首先我们新建一个 package.json,内容尽量简单: { "name": " ...

  2. koa 学习资料

    koa 学习资料 学习资料 地址 koa 中文版 https://koa.bootcss.com/

  3. Koa 学习

    中间件引擎 1234567891011121314151617181920212223242526272829303132333435363738 const Koa = require('koa') ...

  4. Python爬虫学习==>第五章:爬虫常用库的安装

    学习目的: 爬虫有请求库(request.selenium).解析库.存储库(MongoDB.Redis).工具库,此节学习安装常用库的安装 正式步骤 Step1:urllib和re库 这两个库在安装 ...

  5. KOA 学习(二)

    app.listen(...) Koa 应用并非是一个 1-to-1 表征关系的 HTTP 服务器. 一个或多个Koa应用可以被挂载到一起组成一个包含单一 HTTP 服务器的大型应用群. var ko ...

  6. java十五个常用类学习及方法举例

    <code class="language-java">import java.util.Scanner; import java.util.Properties; i ...

  7. ROS常用库(四)API学习之常用common_msgs(下)

    一.前言 承接ROS常用库(三)API学习之常用common_msgs(上). 二.sensor_msgs 1.sensor_msgs / BatteryState.msg #电源状态 uint8 P ...

  8. 爬虫-Python爬虫常用库

    一.常用库 1.requests 做请求的时候用到. requests.get("url") 2.selenium 自动化会用到. 3.lxml 4.beautifulsoup 5 ...

  9. PHP5 的五种常用模式

    PHP5 的五种常用模式. 工厂模式 最初在设计模式 一书中,许多设计模式都鼓励使用松散耦合.要理解这个概念,让我们最好谈一下许多开发人员从事大型系统的艰苦历程.在更改一个代码片段时,就会发生问题,系 ...

  10. Python的常用库

    读者您好.今天我将介绍20个属于我常用工具的Python库,我相信你看完之后也会觉得离不开它们.他们是: Requests.Kenneth Reitz写的最富盛名的http库.每个Python程序员都 ...

随机推荐

  1. PHP面向对象魔术方法之__call函数

    l 基本介绍: (1) 当我们调了一个不可以访问的成员方法时,__call魔术方法就会被调用. (2) 不可以访问的成员方法的是指(1. 该成员方法不存在, 2. 成员方法是protected或者 p ...

  2. 《DSP using MATLAB》Problem 8.37

    代码: %% ------------------------------------------------------------------------ %% Output Info about ...

  3. 第一篇:spring+springMVC项目启动最终笔记(一web.xml)

    1.web应用启动从web.xml开始,首先创建一个全局的上下文(Context),名字叫ServletContext,可以理解为一间图书馆,或一个数据结构(如map,但是比map牛多了),整个结构类 ...

  4. MyBatis - 常用标签与动态Sql

    MyBatis常用标签 ● 定义sql语句:select.insert.delete.update ● 配置JAVA对象属性与查询结构及中列明对应的关系:resultMap ● 控制动态sql拼接:i ...

  5. <scrapy爬虫>爬取quotes.toscrape.com

    1.创建scrapy项目 dos窗口输入: scrapy startproject quote cd quote 2.编写item.py文件(相当于编写模板,需要爬取的数据在这里定义) import ...

  6. 【JZOJ2679】跨时代

    description 钟逆时针而绕,恶物狰狞的倾巢,我谦卑安静地于城堡下的晚祷,压抑远古流窜的蛮荒暗号,而管风琴键高傲的说,那只是在徒劳.我的乐器在环绕,时代无法淘汰我霸气的皇朝. 你无法预言,因为 ...

  7. HTML - 文本标签相关

    <html> <head></head> <body> <!-- 标题标签 : h1到h6, 文字大小依次变小, 加粗显示, 自带换行 标签中的部 ...

  8. Ubuntu下安装和配置Apache2,小编觉得挺不错的,现在就分享给大家

    本篇文章主要介绍了详解Ubuntu下安装和配置Apache2,小编觉得挺不错的,现在就分享给大家,也给大家做个参考.有兴趣的朋友可以了解一下.(http://xz.8682222.com) 在Ubun ...

  9. 0818NOIP模拟测试赛后总结

    又挂了…… 120 rank19. 第一次两个机房考不同的题目.一开始并不知道应该做哪套题目. 不明真相的吃瓜群众决定先点开B套.通读三道题,只是觉得T2好水.似乎是红题难度吧……(后来证明是我读错题 ...

  10. python dict 实现swich

    使用dict实现swich,通过不同的键映射不同的函数. swich = { 'hour1':pred.getper1htable, 'hour6':pred.getper6htable, 'hour ...