Swifton 是一个 Swift Web框架,它受Ruby on Rails启发,可运行在 Linux 和 OS X 上。采用MVC模式。
Controllers(控制器)
beforeAction 和 afterAction 允许注册一个过滤器,可在action之前或之后执行一个filter方法。
class TodosController: ApplicationController {
// shared todo variable used to pass value between setTodo filter and actions
var todo: Todo?
override init() { super.init()
// sets before filter setTodo only for specified actions
beforeAction("setTodo", ["only": ["show", "edit", "update", "destroy"]])
// render all Todo instances with Index template (in Views/Todos/Index.html.stencil)
action("index") { request in
let todos = ["todos": Todo.allAttributes()]
return self.render("Todos/Index", todos)
}
// render Todo instance that was set in before filter
action("show") { request in
return self.render("Todos/Show", self.todo)
}
// render static New template
action("new") { request in
return self.render("Todos/New")
}
// render Todo instance's edit form
action("edit") { request in
return self.render("Todos/Edit", self.todo)
}
// create new Todo instance and redirect to list of Todos
action("create") { request in
Todo.create(request.params)
return self.redirectTo("/todos")
}
// update Todo instance and redirect to updated Todo instance
action("update") { request in
self.todo!.update(request.params)
return self.redirectTo("/todos/\(self.todo!.id)")
}
// destroy Todo instance
action("destroy") { request in
Todo.destroy(self.todo)
return self.redirectTo("/todos")
}
// set todo shared variable to actions can use it
filter("setTodo") { request in
// Redirect to "/todos" list if Todo instance is not found
guard let t = Todo.find(request.params["id"]) else { return self.redirectTo("/todos") }
self.todo = t as? Todo
// Run next filter or action
return self.next
}
}}
Models
(模型)
Swifton是与ORM无关的Web框架,您可以使用您所选择的任何ORM。 Swifton带有简单的运行在内存的MemoryModel类,你可以继承它。示例:
class User: MemoryModel {
}
...
User.all.count // 0
var user = User.create(["name": "Saulius", "surname": "Grigaitis"])
User.all.count // 1
user["name"] // "Saulius"
user["surname"] // "Grigaitis"
user.update(["name": "James", "surname": "Bond"])
user["surname"] // "Bond"
User.destroy(user)
User.all.count // 0
Views(视图
)
Swifton支持模板语言,通过控制器的方法render(template_path, object)调用模板进行显示。
{% for todo in todos %}{{ todo.title }}{{ todo.completed }}ShowEditDestroy{% endfor %}
支持JSON
通过renderJSON(object)方法创建并返回一个JSON对象。
action("show") { request in
return self.respondTo(request, [
"html": { self.render("Todos/Show", self.todo) },
"json": { self.renderJSON(self.todo) }
])
}