diff --git a/spec/std/ecr/ecr_spec.cr b/spec/std/ecr/ecr_spec.cr index 1090dec03557..3e35133f9c6b 100644 --- a/spec/std/ecr/ecr_spec.cr +++ b/spec/std/ecr/ecr_spec.cr @@ -64,4 +64,8 @@ describe "ECR" do ECR.embed "#{__DIR__}/../data/test_template6.ecr", io io.to_s.should eq("string with -%") end + + it ".render" do + ECR.render("#{__DIR__}/../data/test_template2.ecr").should eq("123") + end end diff --git a/src/ecr/macros.cr b/src/ecr/macros.cr index a88848b3b04f..b073605b16d4 100644 --- a/src/ecr/macros.cr +++ b/src/ecr/macros.cr @@ -38,11 +38,11 @@ module ECR end end - # Embeds an ECR file contained in *filename* into the program. + # Embeds an ECR file *filename* into the program and appends the content to + # an IO in the variable *io_name*. # # The generated code is the result of translating the contents of - # the ECR file to Crystal, a program that appends to the IO - # with the given *io_name*. + # the ECR file to Crystal, a program that appends to an IO. # # ```text # # greeting.ecr @@ -59,7 +59,7 @@ module ECR # io.to_s # => "Hello World!" # ``` # - # The `ECR.embed` line basically generates this: + # The `ECR.embed` line basically generates this Crystal code: # # ``` # io << "Hello " @@ -69,4 +69,38 @@ module ECR macro embed(filename, io_name) \{{ run("ecr/process", {{filename}}, {{io_name.id.stringify}}) }} end + + # Embeds an ECR file *filename* into the program and renders it to a string. + # + # The generated code is the result of translating the contents of + # the ECR file to Crystal, a program that appends to an IO and returns a string. + # + # ```text + # # greeting.ecr + # Hello <%= name %>! + # ``` + # + # ``` + # require "ecr/macros" + # + # name = "World" + # + # rendered = ECR.render "greeting.ecr" + # rendered # => "Hello World!" + # ``` + # + # The `ECR.render` basically generates this Crystal code: + # + # ``` + # String.build do |io| + # io << "Hello " + # io << name + # io << '!' + # end + # ``` + macro render(filename) + ::String.build do |%io| + ::ECR.embed({{filename}}, %io) + end + end end