Vapor Web模板和Node's APIs

Web模板和Node's APIs

这里主要介绍web模板。

这里先进行介绍Leaf

  • 这里我们使用web模板直接就有leaf
  • 文件树如下
Hello
├── Config
│   ├── app.json
│   ├── crypto.json
│   ├── droplet.json
│   ├── fluent.json
│   └── server.json
├── Package.pins
├── Package.swift
├── Public
├── README.md
├── Resources
│   ├── Views
│   │   │   └── hello.leaf
├── Public
│   ├── images (images resources)
│   ├── styles (css resources) 
├── Sources
│   ├── App
│   │   ├── Config+Setup.swift
│   │   ├── Controllers
│   │   │   └── PostController.swift
│   │   ├── Droplet+Setup.swift
│   │   ├── Models
│   │   │   └── Post.swift
│   │   └── Routes.swift
│   └── Run
│       └── main.swift
├── Tests
│   ├── AppTests
│   │   ├── PostControllerTests.swift
│   │   ├── RouteTests.swift
│   │   └── Utilities.swift
│   └── LinuxMain.swift
├── circle.yml
└── license

如果是api模板需要进行如下配置

  • Package.swift添加 Leaf-provider
import PackageDescription

let package = Package(
    name: "Helloapi",
    products: [
        .library(name: "App", targets: ["App"]),
        .executable(name: "Run", targets: ["Run"])
    ],
    dependencies: [
        .package(url: "https://github.com/vapor/vapor.git", .upToNextMajor(from: "2.1.0")),
        .package(url: "https://github.com/vapor/fluent-provider.git", .upToNextMajor(from: "1.2.0")),
        .package(url: "https://github.com/vapor/leaf-provider.git", .upToNextMajor(from: "1.1.0")),
    ],
    targets: [
        .target(
            name: "App",
            dependencies: ["Vapor", "FluentProvider", "LeafProvider"],
            exclude: ["Config", "Database", "Public", "Resources"]
        ),
        .target(name: "Run", dependencies: ["App"]),
        .testTarget(name: "AppTests", dependencies: ["App", "Testing"])
    ]
)

  • Config文件夹下droplet添加
    "//": "The type of view renderer that drop.view will use",
    "//": "leaf: Pure Swift templating language created for Vapor.",
    "//": "static: Simply return the view at the supplied path",
    "view": "leaf",
  • 这里需要运行添加 LeafProvider

  • Helloapi/Sources/App/Setup文件夹下Config+Setup.swift文件添加LeafProvider

import FluentProvider
import LeafProvider

extension Config {
    public func setup() throws {
        // allow fuzzy conversions for these types
        // (add your own types here)
        Node.fuzzy = [Row.self, JSON.self, Node.self]

        try setupProviders()
        try setupPreparations()
    }
    
    /// Configure providers
    private func setupProviders() throws {
        try addProvider(FluentProvider.Provider.self)
        try addProvider(LeafProvider.Provider.self)
    }
    
    /// Add all models that should have their
    /// schemas prepared before the app boots
    private func setupPreparations() throws {
        preparations.append(Post.self)
    }
}

  • 这里放几组测试
  • 代码 这里web模板里的。
///
    
        GET /hello/...
        builder.resource("hello", HelloController(view))
        
        /// GET /test/str   测试字符串
        builder.get("test/str") { req in
            let str = "This is test Str"
            return try self.view.make("hello", ["name": str], for: req)
        }
        /// GET /test/array     测试数组
        builder.get("test/array") { req in
            let array = ["one", "two", "three"]
            return try self.view.make("hello", ["array": array])
        }
        /// GET /test/dictionary    测试字典
        builder.get("test/dictionary") { req in
            let arrayModel = [["name":"tom"], ["name":"Tim"], ["name":"LiLei"]]
            return try self.view.make("hello", ["arrayModel": arrayModel])
        }
        /// GET /test/bool      测试bool类型
        builder.get("test/bool") { req in
            let bool = true
            return try self.view.make("hello", ["bool": bool], for: req)
        }
        
  • hello.leaf文件
#extend("base")

#export("title") { Hello, #(name)! }

#export("content") {
    

Hello, #(name)!

现在测试循环 #loop(array, "number") { #(offset). #(number) }
现在测试字典循环 #loop(arrayModel, "model") { #(offset). #(model.name) }
}

这里我们现在进行介绍Node

  • 我们在上面已经可以使用Leaf了、但是有时间基础的字符串、数组、字典已经不能满足我们了。我们需要自定义数据类型。可是我们直接写是识别不了的、所以这里就需要Node来让我们leaf文件可以读取我们自定义的model。

  • 这里也很简单,我们实现 NodeInitializableNodeRepresentable 协议就可以了。

struct Person: NodeInitializable {
    let name: String
    let age: Int

    init(node: Node) throws {
        name = try node.get("name")
        age = try node.get("age")
    }
}

extension Person: NodeRepresentable {
    func makeNode(in context: Context) throws -> Node {
        var node = Node(context)
        try node.set("name", name)
        try node.set("age", age)
        return node
    }
}

  • 当然这里也可以转换json数据让html显示。

你可能感兴趣的:(Vapor Web模板和Node's APIs)