Vapor文档学习六:Leaf

2017-04-19  本文已影响169人  Supremodeamor

Leaf是一种模板语言,目的就是使视图渲染更加容易。其实在其他服务端开发过程中也经常使用模板,比如MustacheExpress
Leaf作为一种可扩展的模板语言,专用于Vapor,至于其与其他模板的区别以及原理我暂时没有研究,咳咳,我们还是先学习怎么使用吧。

Synax(语法)

Structure

Leaf标签由四个元素构成:

根据标签的实现,这4个元素可以有很多不同的用法。我们来看几个例子,说明如何使用Leaf的内置标签:

Using the # token in HTML

#无法转义,在Leaf模板中要使用#()#raw() {}来输出##() => #

Raw HTML

任何Leaf模板的输出都默认被转义,如果不想被转义输出可以使用#raw()标签。#raw() { <a href="#link">Link</a> }=><a href="#link">Link</a>

<i><b>ps:</b>这里体现了Leaf选择用#作为标签的缺点,很容易与html中的链接冲突。</i>

Chaining(链接)

##表示链接标签,可以用在任何标准标签上,如果前一个标签失败,就会执行链接的标签。

#if(hasFriends) ##embed("getFriends")

上面代码中,如果#if(hasFriends)调用失败,就调用#embed("getFriends")(也就是没friends的话就去获取friends)。

Leaf's build-in Tags(Leaf内置标签)

#() #()hashtags #()FTW => # #Hashtags #FTW
#raw() {
    Do whatever w/ #'s here, this code won't be rendered as leaf document and is not escaped.
    It's a great place for things like Javascript or large HTML sections.
}
#equal(leaf, leaf) { Leaf == Leaf } => Leaf == Leaf
#equal(leaf, mustache) { Leaf == Mustache } =>  Leaf == Mustache
Hello, #(name)!
#loop(friends, "friend") {
  Hello, #(friend.name)!
}
Hello, #index(friends, 0)!
Hello, #index(friends, "best")!
#if(entering) {
   Hello, there!
} ##if(leaving) {
   Goodbye!
} ##else() {
   I've been here the whole time.
}

使用这些标签的引入模板的时候不用加.leaf后缀。

这么说你是不是懵逼了?还吃吃个🌰吧:

/// base.leaf
<!DOCTYPE html>
#import("html")

/// html.leaf
#extend("base")

#export("html") { <html>#embed("body")</html> }

/// body.leaf
<body></body>

Leaf最后会将html.leaf按照如下内容渲染:

<!DOCTYPE html>
<html><body></body></html>

我给你剥下栗子皮:
1,base.leaf#import("html")设置了一个插入点,点名使用名为"html.leaf"的模板去填充。
2,html.leaf#extend("base")表明我继承base.leaf,要引入base.leaf的内容。
3,#export("html"){...}就是将{...}中的内容填充到base.leaf中插入点位置。
4,#embed("body")就是把body.leaf模板的内容直接嵌入到当前位置。

Custom Tags(自定义标签)

内置标签肯定无法满足各种复杂场景的需要,当然也满足不了你膨胀的内心,所以自定义标签你得会吧。
看一下现在存在的高级场景应用的标签,一起学习一下创建 Index标签的基础示例,它接收两个参数,一个是数组,一个是索引的下标:

class Index: BasicTag {
  let name = "index"

  func run(arguments: [Argument]) throws -> Node? {
    guard
      arguments.count == 2,
      let array = arguments[0].value?.nodeArray,
      let index = arguments[1].value?.int,
      index < array.count
    else { return nil }
        return array[index]
    }
}

然后将这个标签注册到main.swift中:

if let leaf = drop.view as? LeafRenderer {
    leaf.stem.register(Index())
}

<i><b>ps:</b>Dependencies/Leaf 1.0.7/Leaf/Tag/Models/目录下有每个内置标签类的实现过程。</i>

Note: 不推荐使用除字母或数字之外的字符作为标签名,并且在未来的Leaf版本中可能会禁止使用。

Syntax Highlighting

语法高亮这部分不多说了,Atom编辑器支持Leaf语法。Xcode不支持,可以Editor > Syntax Coloring > HTML改成html语法略微改善。

上一篇 下一篇

猜你喜欢

热点阅读