Merge pull request #27 from f/master

Add render macro to kemal core.
This commit is contained in:
Serdar Dogruyol 2015-12-06 20:45:53 +02:00
commit 2ffb4dccdf
6 changed files with 73 additions and 1 deletions

View file

@ -147,6 +147,22 @@ end
Kemal.config.add_handler CustomHandler.new
```
### Views
You can use ERB-like built-in **ECR** views to render files.
```crystal
get '/:name' do
render "views/hello.ecr"
end
```
And you should have an `hello.ecr` view. It will have the same context as the method.
```erb
Hello <%= env.params["name"] %>
```
## Static Files
Kemal has built-in support for serving your static files. You need to put your static files under your ```/public``` directory.

View file

@ -23,7 +23,7 @@ Kemal means *Mature, grown up* in Turkish.
## How to start?
- [Getting Started Tutorial](./tutorial.md)
- [Using Dynamic Templates (Not Supported Yet)](./templates.md)
- [Using Dynamic Views](./views.md)
- [Parsing HTTP requests and Form Data](./http-requests.md)
- [Uploading Files](./upload.md)
- [Serving Static Files](./statics.md)

28
docs/views.md Normal file
View file

@ -0,0 +1,28 @@
# Views
You can use ECR to build views. Kemal serves a `render` macro to use built-in `ECR`
library.
## Writing Views
The ECR is actually ERB.
```
src/
views/
hello.ecr
```
Write `hello.ecr`
```erb
Hello <%= your_name %>
```
## Embedding View File
```crystal
get '/' do |env|
your_name = "Kemal"
render "views/hello.ecr"
end
```

1
spec/asset/hello.ecr Normal file
View file

@ -0,0 +1 @@
Hello <%= env.params["name"] %>

13
spec/view_spec.cr Normal file
View file

@ -0,0 +1,13 @@
require "./spec_helper"
describe "Views" do
it "renders file" do
kemal = Kemal::Handler.new
kemal.add_route "GET", "/view/:name" do |env|
render "spec/asset/hello.ecr"
end
request = HTTP::Request.new("GET", "/view/world")
response = kemal.call(request)
response.body.should contain("Hello world")
end
end

14
src/kemal/view.cr Normal file
View file

@ -0,0 +1,14 @@
# Kemal render uses built-in ECR to render methods.
## Usage
# get '/' do
# render 'hello.ecr'
# end
require "ecr/macros"
macro render(filename)
String.build do |__view__|
embed_ecr {{filename}}, "__view__"
end
end