diff --git a/README.md b/README.md index 2cb19e8..175be40 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/docs/README.md b/docs/README.md index 1f1618a..60dfe63 100644 --- a/docs/README.md +++ b/docs/README.md @@ -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) diff --git a/docs/views.md b/docs/views.md new file mode 100644 index 0000000..79315b8 --- /dev/null +++ b/docs/views.md @@ -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 +``` diff --git a/spec/asset/hello.ecr b/spec/asset/hello.ecr new file mode 100644 index 0000000..355a5a2 --- /dev/null +++ b/spec/asset/hello.ecr @@ -0,0 +1 @@ +Hello <%= env.params["name"] %> diff --git a/spec/view_spec.cr b/spec/view_spec.cr new file mode 100644 index 0000000..0f38748 --- /dev/null +++ b/spec/view_spec.cr @@ -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 diff --git a/src/kemal/view.cr b/src/kemal/view.cr new file mode 100644 index 0000000..813cf98 --- /dev/null +++ b/src/kemal/view.cr @@ -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