jade模板引擎

Jade是一款高性能简洁易懂的模板引擎,Jade是Haml的Javascript实现,在服务端(NodeJS)及客户端均有支持。

官网 http://jade-lang.com/

习惯jade的最好办法:找一个已写好的html代码,用jade重写一遍

但是如果你是新手,而且直接拿jade写没有写过的页面,那么你会死的很难看

规则说明

标签简写

  1. 比如`<p>`写成`p`

jade里的

  1. p

等于

  1. <p></p>

属性放到括号里

  1. 比如`<div class='left_panel'>`写成`div`

标签只有1个属性的情况

jade里的

  1. div(class='left_panel')

等于

  1. <div class='left_panel'>

标签如果有多个属性的情况

jade里的

  1. div(id='this_is_div_id',class='left_panel')

等于

  1. <div id='this_is_div_id' class='left_panel'>

value写法

比如html代码

  1. <p>this is a p tag</p>

在jade里需要成

  1. p this is a p tag

一定要注意p标签后面的空格,如果没有空格是错的

但是如果标签有括号属性的,可以没有空格

  1. button(id='create_exam_on_server_btn')生成问卷

建议:不管有没有标签,都要再写value的时候加一个空格

没有空行

jade里不允许有空行,比如我们在html里可以写的很随意

  1. <p>前端专业八级考试</p>
  2. <p>友情提示:不准携带通讯工具,不准交头接耳、 一经发现,取消考试成绩,并终生禁止再次参与本考试!一定要记得哦!</p>

但是在jade里,是不允许出现空行,你只能这样写

  1. p 前端专业八级考试
  2. p 友情提示:不准携带通讯工具,不准交头接耳、 一经发现,取消考试成绩,并终生禁止再次参与本考试!一定要记得哦!

好处是代码不能太随意,因为编译不通过,jade其实是把空行当做编译一个标签的条件,所以你只能遵守规则玩

层级嵌套

比如我们常见的html代码

  1. <ul id='all_qs'>
  2. <li>1</li>
  3. <li>2</li>
  4. <li>3</li>
  5. </ul>

在jade里需要成

  1. ul(id='all_qs')
  2. li 1
  3. li 2
  4. li 3

这个实现原理很简单,就是利用缩进来判断包含关系。

缩进有2种方式

  1. 空格
  2. tab(推荐使用tab)

变量

  1. doctype html
  2. html
  3. head
  4. title= title
  5. link(rel='stylesheet', href='/stylesheets/style.css')
  6. script(src='/javascripts/jquery.min.js')
  7. body
  8. block content

这里的title= title代码里的=代表后面接的是变量。而且在子页面通过extends继承的也可以使用该变量。

插写法

  1. p #user #{name} #{email}

这种是和ruby的语法一样的

反转义变量!{html}

  1. var html = "<script></script>"
  2. !{html}

注释

块注释

  1. body
  2. //
  3. #content
  4. h1 CSSer,关注Web前端技术

条件注释

  1. body
  2. /if IE
  3. a(href='http://www.mozilla.com/en-US/firefox/') Get Firefox

块扩展

块扩展允许创建单行的简洁嵌套标记,下面的示例与上例输出相同:

ul
li.first: a(href=’#’) foo
li: a(href=’#’) bar
li.last: a(href=’#’) baz

布局

这里引一个java里的sitemesh布局框架

jade - 图1

这个其实和jade的布局概念差不多,装饰模式不见得比编译更有优势

布局最核心的是留空,其他的都放到layout里,复用layout。。。

下面具体看看

layout.jade

  1. doctype html
  2. html
  3. head
  4. title= title
  5. link(rel='stylesheet', href='/stylesheets/survey.css')
  6. script(src='/javascripts/jquery.min.js')
  7. script(src='/javascripts/jquery.min.js')
  8. script(src='/javascripts/survey.js')
  9. body
  10. div(class='left')
  11. block left_content
  12. div(class='main')
  13. block main_content

集成

  1. extends ../layout
  2. block left_content
  3. h1= title
  4. button(id='create_exam_on_server_btn')生成问卷
  5. hr
  6. p all 题目
  7. ul(id='all_qs')
  8. block main_content
  9. h1= title
  10. div(class='create_exam')
  11. select(name='is_ad')
  12. option(value='true') true
  13. option(value='false',selected) false
  14. br
  15. input(type='text' name='all_name' value='前端技术专业八级考试')
  16. br
  17. input(type='text' name='all_desc' value='友情提示:不准携带通讯工具,不准交头接耳、 一经发现,取消考试成绩,并终生禁止再次参与本考试!一定要记得哦!')
  18. br
  19. input(type='text' name='all_weixin_name' value='all_weixin_name')
  20. br
  21. input(type='text' name='all_weixin_id' value='188888888')
  22. button(id='create_exam_btn')创建试卷
  23. div(class='show_exam')
  24. p 前端专业八级考试
  25. p 友情提示:不准携带通讯工具,不准交头接耳、 一经发现,取消考试成绩,并终生禁止再次参与本考试!一定要记得哦!

说明

  • extends是指当前jade页面继承自哪个layout
  • block是指定义此处有模板块

这个是最最核心的概念,也是最最实用的~~

结合include就是神器~~

each

首先服务器端要返回数据

  1. router.get('/list', function(req, res) {
  2. var Survey = req.models.Survey;
  3. Survey.find_list({},function(surveys){
  4. res.render('survey/list', { title: '试卷列表',surveys: surveys });
  5. });
  6. });

然后jade中

  1. ul
  2. each item in surveys
  3. li= item.name
  4. a(href= item.static_page_name)= item.name

注意等号

  • li= item.name(无属性直接赋值变量)
  • a(href= item.static_page_name)= item.name(有属性,赋值变量)

include

在ruby里叫partial

可以把很多公用的部分,拆成partial

include分2种

  • 静态文件
  • 带data参数的

静态文件

  1. include ./includes/head.jade

带data参数的

  1. include activity

它会把上下文的 activity 作为数据参数,传给

  1. - var _action = activity._action == 'edit' ? '#' : '/activities/'
  2. - var _method = activity._action == 'edit' ? "" : "post"
  3. - var _type = activity._action == 'edit' ? "button" : "submit"
  4. - var onClick = activity._action == 'edit' ? "click_edit('activity-" + activity._action + "-form','/activities/" + activity._id + "/')" : ""
  5. form(id='activity-#{ activity._action}-form',action="#{_action}", method="#{_method}",role='form')
  6. each n in ['activity.title','activity.product_name','activity.product_count','activity.price','activity.detail','activity.expire_days','activity.start_date','activity.end_date','activity.owner_id','activity.created_at']
  7. - m = eval(n);
  8. div(class="field")
  9. label #{n.split('.')[1]} #{m}
  10. br
  11. input(type='text',name="#{n.split('.')[1]}" ,value="#{ m == undefined ? '' : m }")
  12. div(class="actions")
  13. input(type='#{_type}',value='Submit',onClick='#{onClick}')

内嵌script

在html里直接使用script写代码,虽然不推荐,但偶尔还是会用的的

比如weui里的模板

  1. script.
  2. function test(){
  3. console.log('xxxx');
  4. }

注意script后面的.

最佳实践

jade效率基准测试&预编译&nodejs工作流

我想出的满足当下场景下需求(在使用了预编译的同时实现实时刷新)的办法是: nodejs中fs.watch监控jade文件进行re-compile + gulp中watch文件然后延时触发lr.changed().

示例

  1. // Let's first see how to inject JS logic into your JADE templates
  2. // JADE supports its own constructs for conditionals and loops to make your templates cleaner :) Let's see it in action!
  3. - var users = [{name: 'foo', role: 'admin'}, {name: 'bar', role: 'manager'}, {name: 'baz', role: 'technician'}]
  4. h2 Users
  5. // Neat! There's another construct called `each`
  6. // Also there is `unless` which is equivalent to if (!expr)
  7. // Let's use that and swap a bit of code
  8. each user, index in users
  9. unless user.role === 'admin'
  10. p #{user.name} is not an "admin"
  11. else
  12. p #{user.name} is an "admin"
  13. // Let's take a look at `case` statements now
  14. h3 case
  15. case users[2].name
  16. when 'admin'
  17. p User is an admin
  18. when 'manager'
  19. p User is a manager
  20. when 'technician'
  21. p User is a technician
  22. default
  23. p User is a customer!
  24. h3 mixins
  25. // mixins are pieces of code that you can reuse as functions. they may or may not accept arguments
  26. mixin fruits
  27. ul
  28. li Apple
  29. li Banana
  30. li Orange
  31. h2 Fruits
  32. mixin fruits
  33. mixin users(name, role)
  34. li(attributes) #{name} has a role of #{role}
  35. // Another way to call mixins that provides with a few extra features that you're going to see in a second.
  36. // The attributes, id, class have been added to the li's. You can style them from CSS now.
  37. +users(users[0].name, users[0].role)#admin
  38. +users(users[1].name, users[1].role).manager
  39. +users(users[2].name, users[2].role)(title="technician")
  40. // Mixins are excellent for dropdowns
  41. mixin user_list(name)
  42. option(value="#{name}") #{name}
  43. select
  44. for user in users
  45. +user_list(user.name)
  46. // Great! Now finally let's take a look at "filters". filters must be prefixed with ':', for example ':coffeescript' or ':markdown'. Jade currently supports :stylus, :less, :markdown, :cdata and :coffeescript. Let's see how to use the coffee filter.
  47. :coffeescript
  48. (->
  49. document.querySelectorAll('.manager')[0].style.color = 'blue'
  50. )()
  51. // Some random piece of code but you get the idea :)
  52. // That's all!

总结

  • 使用tab而非space
  • 不管有没有属性,标签和value之间都要有空格
  • 利用layout定义布局模板
  • 利用include来引用公共模块
  • 预编译,提高模板执行效率
  • livereload,提高开发效率